Thursday, April 19, 2012

Difference between == and .equals

Hi All,

In this post, I will explain you the difference between == and .equals() method while comparing two values.

Let us take an example :

package testapp;

public class TestString {
    public static void main(String[] args) {
        TestString testString = new TestString();
                String s1, s2, s3;
        s1 = "abc";
        s2 = new String("abc");
        s3= new String("abc").intern();
        if(s1.equals(s2))
             System.out.println("s1.equals(s2) is TRUE");
        else
             System.out.println("s1.equals(s2) is FALSE");
       
        if(s1==s2)
             System.out.println("s1==s2 is TRUE");
           else
             System.out.println("s1==s2 is FALSE");
       
        if(s1.equals(s3))
             System.out.println("s1.equals(s3) is TRUE");
        else
             System.out.println("s1.equals(s3) is FALSE");
       
        if(s1==s3)
             System.out.println("s1==s3 is TRUE");
           else
             System.out.println("s1==s3 is FALSE");



        if(s2.equals(s3))
             System.out.println("s2.equals(s3) is TRUE");
        else
             System.out.println("s2.equals(s3) is FALSE");
       
        if(s2==s3)
             System.out.println("s2==s3 is TRUE");
           else
             System.out.println("s2==s3 is FALSE");
    }
}



The output of the above program would be :

s1.equals(s2) is TRUE
s1==s2 is FALSE
s1.equals(s3) is TRUE
s1==s3 is TRUE
s2.equals(s3) is TRUE
s2==s3 is FALSE

I will explain you why this happens. When you compare two strings variables - s1, s2 using .equals() method, it precisely compares the values(ie., content) that these variables contains. So, if the values of the variables are same, then it returns true, else it returns false


                      When you compare the two strings variables - s1, s2 using == , you will get false as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' every time a new object is created.


                   A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the #equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. Hence, the result.

No comments:

Post a Comment