Possible Duplicate:
How do I compare strings in Java?
I am new to Java and I have difficulties in understanding String comparison. Can anyone explain the differences between the following scenarios?
Scenario 1 :
String a = "abc";
String b = "abc";
When I run the if(a == b) it returns true.
Scenario 2 :
String a = new String("abc");
String b = new String("abc");
and run if(a == b) then it returns false.
What is the difference?
==operator compares the references of two objects in memory. If they point to the same location then it returns true.Stringobject in java are Immutable, so when you create Strings like in scenario1 then it didn’t create new string. It just points the second string to the memory location of first string.However,
.equals()method compares the content of the String. When strings has same value then this method returns true.So, in general it is recommended to use
equals()method instead of==.