-3

Why does this return false? How can I get it to return true?

public class Test {
    public static void main(String [] args) {
        char character = 'X';
        String x = Character.toString(character);
        System.out.println(x == "X"); // returns false
    }
}
vuolen
  • 464
  • 4
  • 12
  • 1
    The most duplicate SO question ever. I wonder how on earth Java tutorials out there are written that this question doesn't cease to reappear on a way too regular basis. – fge Jul 04 '13 at 11:16
  • 4
    I'm crying.. again :__( – Maroun Jul 04 '13 at 11:19

4 Answers4

4

Use the String.equals(otherString) function to compare strings, not the == operator.

The reason is that == just compares object references,where as .equals() checks equality.

 System.out.println(x.equals("X"));
Maroun
  • 94,125
  • 30
  • 188
  • 241
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You cannot compare strings in Java with == in general. Use x.equals("X"). Otherwise you're using reference equality and are in fact testing that both x and "X" are the same reference (which is unlikely to be the case).

Joey
  • 344,408
  • 85
  • 689
  • 683
1

Because Character.toString(character) returns a new String . Hence x =="X" is false. == compares references , not contents. To compare String , use equals() method.

System.out.println(x.equals("X"));

Character.toString(character); calls String.valueOf(character), whose code is :

public static String valueOf(char c) {
  char data[] = {c};
  return new String(0, 1, data); // new String object created here
}

Hence your comparison of object reference using == fails .

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

== operator in Java checks whether the two references are pointing to the same object or now. Which is false in your case. For String comparison, use equals() or equalsIgnoreCase()

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102