Alex Rivera | Logout

Java comparison with == of two strings is false?

Asked 2009-06-15T12:47:26.537
45

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?

Edit
Report

2 Answers

13

The following prints out "true";

String s = "231";
if(s == "231")
{
    System.out.println("true");
}
else
{
    System.out.println("false");
}

This is because Strings are not mutable and java will try and save as much space as possible, so it points both to the same memory reference.

However, the following prints out "false":

String s = new String("231");
if(s == "231")
{
    System.out.println("true");
}
else
{
    System.out.println("false");
}

new will force it to store the string in a new memory location.

By the way, you should ALWAYS use .equals() to compare strings (for cases just like this one)

answered 2009-06-15T17:57:30.983
7

Use equals method: parts[0].equals("231"). == operator compares object references.

answered 2009-06-15T12:50:03.363

Your Answer