Reputation: 6241
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
?
Upvotes: 1
Views: 336
Reputation: 61578
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 String
comparison in java is case-sensitive, so you might also want to take a look at the equalsIgnoreCase
method.
Upvotes: 10
Reputation: 12633
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");
Upvotes: 0
Reputation: 691
(p + q).intern() == "seventeen"
intern will return the string from the pool
Upvotes: 4
Reputation: 26271
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.
Upvotes: 0