0

Why is it that comparison of two strings having identical contents (s1==s2) returns true but (s3==s4) returns false if we initiate s1 and s2 with "=" but s3 and s4 with String constructor? #JAVA Like

String s1="s";
String s2="s";

String s3= new String("s");
String s4= new String("s");
Makoto
  • 104,088
  • 27
  • 192
  • 230
Umair Ayub
  • 19,358
  • 14
  • 72
  • 146

1 Answers1

0

String s1 is a REFERENCE not an OBJECT. This means when you compare s1 == s2 you are comparing the references, not the contents of what those references point.

When you have two String literals which are the same, they are cached and the same object is used. This is done to save space. This means two string literals which have the same contents point to the same object.

When you create two new objects, they have different references so they are not equal, even if s3.equals(s4) is true.

I suggest you look at the String.intern() method which details how Strings are pooled.

So these are all true.

s1 == s2;
s1 == s3.intern();
s3.intern() == s4.intern();
s1 == s1.intern();
s1 == s1.intern().intern().intern();
s3 != s3.intern();

In hindsight, I think Java should have had a === for comparing references and == for comparing contents i.e. calling equals as this is a common source of confusion for developers who don't understand the difference between references and objects in Java.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 2
    (1) I believe [`intern()`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()) needs to be mentioned. (2) Your proposal for `===` will require new syntax for operator (not method) overload. – PM 77-1 Nov 10 '13 at 17:29
  • @PM77-1 It is too late to change as `==` is used in quite a bit of code now. It is common for beginners in Java to expect that `==` compares the contents of objects referenced. – Peter Lawrey Nov 10 '13 at 17:34