Please navigate to the bottom of the page for Table of Contents

Sunday, June 19, 2011

JAVA equals() versus == operator

Question: Show the difference between == and equals() method with an example.

The comments in the program below are self explanatory and should help you figure out the subtleties of new object creation and the == operator versus equals() method.

public class CompareQuestion 
{
    public static void main(String[] args) 
    {
        String s1 = new String("A"); //not recommended, use String s1 = "A"
        String s2 = new String("A"); //not recommended, use String s2 = "A"
    
        //standard: follows the == and equals() rule like plain java objects.
        if (s1 == s2) 
        {   //shallow comparison, never reaches here
            System.out.println("references/identities are equal"); 
        }
    
        if (s1.equals(s2)) 
        {   //deep comparison, this line is printed
            System.out.println("values are equal"); 
        }
    
        //variation: does not follow the == and equals rule
        String s3 = "A"; //goes into a String pool.
        String s4 = "A"; //refers to String already in the pool.
        if (s3 == s4) 
        {   //shallow comparison, this line is printed
            System.out.println("references/identities are equal"); 
        }
    
        if (s3.equals(s4)) 
        {   //deep comparison, this line is also printed
            System.out.println("values are equal"); 
        }
    }
}

Note: When you create a new string object by using the new String(“A”), a new String instance is created each time it is executed.

No comments:

Post a Comment