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
Well, how can I demonstrate the problem using the == operator when comparing Strings (or Objects) in Java ?
Here a way:
String s = "ab";
String t = new String("ab");
System.out.println(s == t); // false
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:
Integer s = -128;
Integer t = -128;
System.out.println(s == t);
will print true
, while:
Integer s = -129;
Integer t = -129;
System.out.println(s == t);
prints false
!
JAVA maintains a String Pool in the heap space, where it tries to have multiple references for same values if possible.
Had you written :
String s1 = new String ("Hello");
String s2 = new String ("Hello");
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.
The compiler does some optimizations in your case so that s1
and s2
are really the same object. You can work around that by using
String s1 = new String( "Hello" );
String s2 = new String( "Hello" );
Then you have two distinct objects with the same text content.