String1 == String2?? Why is it wrong?

String s1 = “Apple”;
String s2 = new String(“Apple”);
String s3 = “Apple”;

Are s1, s2 and s3 same?

Logically, all are the same, but in JAVA they aren’t. Check and see!

To answer the above question there is a simple concept in JAVA (at least) which we have to understand.

For simplicity, lets say s1, s2 and s3 are declared in a function and are local variables. Hence, they reside in heap memory. There is a special place in heap memory called, “String Constant Pool“.

Whenever we create a string using = operator (in the case of s1 or s3 above), it is created in String Constant Pool. If we create a string using String Constructor (in case of s2 above), it is not created in String Constant Pool. In String Constant Pool, same string (case and spelling wise) resides only once in memory. All the variables (objects) refer to it.

So, s1 and s3 refer to the same location in String Constant Pool as we are storing the same in both i.e ‘Apple’.

Whenever we use the == operator with variables, it compares the references. So,

  • s1 is equal to s3
  • s1 is not equal to s2
  • s3 is not equal to s2

But equals() method in String class compares the actual characters and not references.

Now you know why it is not advisable to use == while comparing strings in JAVA.

Leave a comment