I want to demonstrate with a few line of code that in Java, that to compare two strings (String
), you have to use equals()
instead of the operator ==
.
Here is something I tried :
public static void main(String Args[]) {
String s1 = "Hello";
String s2 = "Hello";
if (s1 == s2)
System.out.println("same strings");
else
System.out.println("different strings");
}
I was expecting this output : different strings
, because with the test s1 == s2
I'm actually comparing two references (i.e. addresses) instead of the objet's content.
But I actually got this output : same strings
!
Browsing the internet I found that some Java implementation will optimize the above code so that s1
and s2
will actually reference the same string.
Well, how can I demonstrate the problem using the ==
operator when comparing Strings (or Objects) in Java ?
JAVA maintains a String Pool in the heap space, where it tries to have multiple references for same values if possible.
Had you written :
it would have given you the output : "different strings".'new' keyword creates a new object reference while not giving new will first check the string pool for its existence.
Here a way:
Also be careful when comparing primitive wrappers and using auto-boxing: Integer (and Long) for instance caches (and re-uses!) the values -128..127. So:
will print
true
, while:prints
false
!The compiler does some optimizations in your case so that
s1
ands2
are really the same object. You can work around that by usingThen you have two distinct objects with the same text content.