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
?
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
?
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.
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.
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");