0

I'm trying to compare a string and a character (after converting it to a string). The code is not working like I expect it to work.

package main;
import java.lang.Character;

public class Main {
    public static void main(String[] args) {
        char myChar = 'a';
        String myString = "a";
        if(myString == Character.toString(myChar)) {
            System.out.println("This SHOULD work! But it doesn't.");
        } else {
            System.out.println("This SHOULDN'T work! But it does.");
        }
    }
}

What am I doing wrong here?

Bonz0
  • 373
  • 2
  • 5
  • 17

4 Answers4

5

Use:

if(myString.equals(Character.toString(myChar)))

instead of:

if(myString == Character.toString(myChar))

== tests whether the two references pointing to the same object in the memory or not, while equals method checks if the two references pointing to the same object OR they have the same contents.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 4
    I think SO needs to have a feature where if a question includes the word "string" as well as "compare", "comparison" or "equals", then a huge blinking red box comes up and tells you to use `equals` instead of `==`. – yshavit Jun 30 '12 at 17:33
  • @yshavit indeed, this question is being asked almost every day :) – Eng.Fouad Jun 30 '12 at 17:37
  • I apologize if the question has already been asked. I tried searching for it, but couldn't find it. Thanks for the answer though. – Bonz0 Jul 01 '12 at 01:24
1

For comparing equality of string ,We Use equals() Method. There are two ways of comparison in java. One is "==" operator and another "equals()" method . "==" compares the reference value of string object whereas equals() method is present in the java.lang.Object class. This method compares content of the string object. .

So in your case, its better to use .equals() instead if "==".

Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178
0

Do not use == operator to compare strings. While string literals embedded to source code can be compared with this operator, this approach does not work for string objects, you get dynamically.

It is because == compares references to objects, not the object values.

Use String.equals() method to compare strings objects.

0

General rule for string comparison:

  • == compares references (some sort of pointers if you are coming from C)
  • equals compares the content.

In your case, you are comparing two different references to two different objects and that's why it is returning false where you expect it to be true. For string comparison, always use the String.equals() method

GETah
  • 20,922
  • 7
  • 61
  • 103