Difference between “==” and “equals(…)” in comparing Java String objects?


Explain the difference between “==” and “equals(…)” in comparing Java String objects?


It's a very tricky question, number of times we have missed in the interview. Ok, let's start from the basics.
String is a class in java, not a datatype. it's completely immutable that's why we can not modify. It follows the string Pool Concept as we know.


When you use “==” (i.e. shallow comparison), you are actually comparing the two object references to see if they point to the same object. When you use “equals(…)”, which is a “deep comparison” that compares the actual string values. For example:

public class StringEquals {
 public static void main(String[ ] args) {
   String s1 = "PREJAVA";
   String s2 = new String(s1);
   String s3 = "PREJAVA";

   System.out.println(s1 + " equals " + s2 + "--> " +  s1.equals(s2)); //true

   System.out.println(s1 + " == " + s2 + " --> " + (s1 == s2)); //false
   System.out.println(s1 + " == " + s3+ " -->" + (s1 == s3)); //true
 }
}

 
The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer, thus the contents of the two String objects are identical, but they are 2 distinct objects having 2 distinct references s1 and s2. This means that s1 and s2 do not refer to the same object and are, therefore, not ==, but equals( ) as they have the same value “Hello”. The s1 == s3 is true, as they both point to the same object due to internal caching. The references s1 and s3 are interned and points to the same object in the string pool.

Related Articles

post a comment