1

I have the following Java code:

String p = "seven";
String q = "teen";
p + q == "seventeen";

Why does the last line return false and not true?

freshest
  • 6,229
  • 9
  • 35
  • 38
  • This may be a duplicate of http://stackoverflow.com/questions/1858569/java-why-can-string-equality-be-proven-with – sverre May 25 '11 at 14:12

4 Answers4

10

Because you should use the equals method for String comparison. The == operator compares the object references, and those are unique for each object. You would only get true for a == comparison when comparing an object to itself.

Try (p + q).equals("seventeen");

Note, that Stringcomparison in java is case-sensitive, so you might also want to take a look at the equalsIgnoreCase method.

kostja
  • 60,521
  • 48
  • 179
  • 224
4

(p + q).intern() == "seventeen"

intern will return the string from the pool

anfy2002us
  • 683
  • 1
  • 7
  • 15
0

When comparing Strings, you must use the String method equals or equalsIgnoreCase, otherwise you are comparing objects. since p + q is a different object than "seventeen", your result will be false.

james
  • 26,141
  • 19
  • 95
  • 113
0

Because == is reference equality and not logical equality. Strings are immutable so you are getting new Strings, which won't be the same location in memory. Try:

String p = "seven";
String q = "teen";
(p + q).equals("seventeen");
planetjones
  • 12,469
  • 5
  • 50
  • 51