Java comparison with == of two strings is false?

omg picture omg · Jun 15, 2009 · Viewed 80k times · Source

String parts is String[6]:

["231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"]

But when I compare parts[0] with "231":

"231" == parts[0]

the above result is false,

I'm confused, so could anybody tell me why?

Answer

coobird picture coobird · Jun 15, 2009

The == operator compares the object references, not the value of the Strings.

To compare the values of Strings, use the String.equals method:

"231".equals(parts[0]);

This is true with any other object in Java -- when comparing values, always use the equals method rather than using the == operator.

The equals method is part of Object, and should be overridden by classes which will be compared in one way or another.