==, === and equals()

==, === and equals()

Comparison stories of Java and JavaScript

Well, == and equals() are from Java and === is for JavaScript.

Anyways, they all help in comparing objects and values and make development easier.

Object comparison is the part of parcel of any program. While == superficially compares two objects, just comparing the memory references, equals() gives the power to override the way comparison is done between two objects.

Strings make it easy to understand this.

public class Demo6 {
    public static void main(String...strings) {
//a & b point to the same value in the string pool
        String a = "Hello";
        String b = "Hello";
//This creates a new string in a different memory in the string pool
        String c = new String(a);
        System.out.println("(a==b) :: " + (a==b)); //true
        System.out.println("(a.equals(b)) :: " + (a.equals(b))); //true
        System.out.println("(a==c) :: " + (a==c)); //false
        System.out.println("(a.equals(c)) :: " + (a.equals(c))); //true
    }
}

Generally, the first statement in any overriding equals() is to compare if both the objects point to the same memory. Only then the actual comparison as per the requirement is done.

class Compare {
    int a;
    String b;
    Compare(int a, String b) {
        this.a = a;
        this.b = b;
    }
    @Override
    public boolean equals(Object c) {
        //The memory reference comparison
        if (this == c)
            return true;
        if (c == null)
            return false;
        //The type comparison
        if (this.getClass() != c.getClass())
            return false;
        Compare c1 = (Compare) c;
        //The 'actual' comparison
        return c1.a == this.a && c1.b.equals(this.b);
    }
    @Override
    public int hashCode() {
        return a;
    }
}
public class Demo7 {
    public static void main(String...strings) {
        Compare c1 = new Compare(1, "Hello");
        Compare c2 = c1;
        Compare c3 = new Compare(1, "Hello");
        System.out.println("(c1==c2) :: " + (c1==c2)); //true
        System.out.println("(c1.equals(c2)) :: " + (c1.equals(c2))); //true
        System.out.println("(c1==c3) :: " + (c1==c3)); //false
        System.out.println("(c1.equals(c2)) :: " + (c1.equals(c3))); //true
    }
}

Thus, equals() behaves just like an === (strict equality checker) in JS.

'2' == 2 //true
'2' === 2 //false
'hello' == 'hello' //true
'hello' === 'hello' //true
'hello' == new String('hello') //true
'hello' === new String('hello') //false
'2' == new Number(2) //true
'2' === new Number(2) //false
2 == new Number(2) //true
2 === new Number(2) //false

Compare objects, not people!

Happy coding!