Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java comparison with == of two strings is false? [duplicate]

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?

like image 580
omg Avatar asked Jun 15 '09 12:06

omg


People also ask

Why does == evaluate to false in Java?

This is because the two Integer objects have the same value, but they are not the same object.

What happens when you use == to compare strings in Java?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

Can we compare 2 strings using == in Java?

We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method.

When comparing strings Why is == not a good idea?

Using the “==” operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because “==” only checks the referential equality of two Strings, meaning if they reference the same object or not.


1 Answers

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.

like image 60
coobird Avatar answered Sep 29 '22 20:09

coobird