freshest
freshest

Reputation: 6241

Unexpected Boolean Result

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

Answers (4)

kostja
kostja

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 Stringcomparison in java is case-sensitive, so you might also want to take a look at the equalsIgnoreCase method.

Upvotes: 10

planetjones
planetjones

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

anfy2002us
anfy2002us

Reputation: 691

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

intern will return the string from the pool

Upvotes: 4

james
james

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

Related Questions