How to compare any two strings in JAVA ?

Equals to(==) compares Object reference while .equals() compares String value.

However == gives illusions of comparing String values, as in following cases:

String first="Ram";
String second="Ram";
if(first==second) ==> true

It's because when you create any String literal, JVM first searches for that literal in String pool, and if it finds a match, that same reference will be given to the new String. because of this, we get

(first==second) ==> true

                       String Pool
     first -----------------> "Ram" <----------------- second
Now == fails in following case - 

String a="Ram";
String b=new String("Ram");

if (a==b) ==> false
The == operator checks to see if the two strings are exactly the same object. In this case for new String("Ram") the statement new String will be created in heap that reference will be given to b, so b will be given reference in heap not in String Pool.

So a is pointing to String in String pool while b is pointing to String in heap, because of that we are getting

if(a==b) ==> false.

                (String Pool)
     "Ram" <----------------- a

     "Ram" <----------------- b
While .equals() always compares value of String so it gives true in both cases
String first="Kanha";
String second="Kanha";

if(first.equals(second)) ===> true

String a="Kanha";
String b=new String("Kanha");
if(a.equals(b)) ===> true

The .equals() method will check if the two strings have the same value. So using .equals() is always better.

Blog Category: