What is Difference Between "==" and "equals" method in Java

Main difference between == and equals in Java is , "==" is used to compare primitives while equals() method is used to check equality of objects. Another difference between them is that, If both "==" and equals() is used to compare objects than == returns true only if both references points to same object while equals() can return true or false based on its overridden implementation.One of the popular cases is comparing two String in Java in which case == and equals() method return different results.

 

Comparing String with == and equals

public class JavaEquals {
    
    public static void main(String[] args)
    {
        String myjava = new String("My Java Course");
        String javaStr = new String("My Java Course");

        //since two strings are different object result should be false
        boolean result = myjava == javaStr;
        System.out.println("Comparing two strings with == operator: " + result);

        //since strings contains same content , equals() should return true
        result = myjava.equals(javaStr);
        System.out.println("Comparing two Strings with same content using equals method: " + result);

        javaStr = myjava;
        //since both homeLoan and personalLoand reference variable are pointing to same object
        //"==" should return true
        result = (myjava == javaStr);
        System.out.println("Comparing two reference pointing to same String with == operator: " + result);


    }
}

 

Output

Comparing two strings with == operator: false
Comparing two Strings with same content using equals method: true
Comparing two reference pointing to same String with == operator: true

 

Comparing two objects with "==" and equals

public class JavaEquals {
    
    static boolean result;
    public static void main(String[] args)
    {
      
        Object obj1 = new Object();
        Object obj2 = new Object();

        // == should return false
        result = (obj1==obj2);
        System.out.println("Comparing two different Objects with == operator: " + result);

        //equals should return false because obj1 and obj2 are different
        result = obj1.equals(obj2);
        System.out.println("Comparing two different Objects with equals() method: " + result);

        // "==" should return true because both obj1 and obj2 points same object
        obj1=obj2;
        result = (obj1==obj2);
        System.out.println("Comparing two reference pointing to same Object with == operator: " + result);


    }
}

 

Output

Comparing two different Objects with == operator: false
Comparing two different Objects with equals() method: false
Comparing two reference pointing to same Object with == operator: true