I had an interesting conversation with one of my team mate.
Is CONSTANT.equals(VARIABLE)
faster than VARIABLE.equals(CONSTANT)
in Java?
If we compare CONSTANT key(Left side of equals method) with any Object(Right side of equals method) then compiler can do check comparison and give the expected result, but if we do vice versa Object((Left side of equals method)) comparison with Constant key((Right side of equals method)) then your program might through the NULL POINTER EXCEPTION.
public static void main(String[] args) {
String CONSTANT_KEY = "JAVA";
String string = null;
// CASE 1
if (CONSTANT_KEY.equals(string)) {
System.out.println("I am in if block");
}
// CASE 2
if (string.equals(string)) {
System.out.println("I am in if block");
}
}
In above code case 1 is always safe to compare the objects to avoid NULL POINTER EXCEPTION instead of case 2.