Keeping constants on the left

It is often said that when using null checks, or equating variables, the constant values must be kept on left hand side.

Until now, I’ve believed that it is a myth. But today I sat down to peel out the truth.

Why one should follow it?

Lets take the following example,

String var = null;

now,

var.equals(“constant”) // NullPointerException

“constant”.equals(var) // False, No NullPointerException

This happens because the equals method is usually written to include the null check in it. Saving us from the dreadful null pointer exception in this particular scenario. Also, the redundant null check could be avoided. (One in equals and the other in our explicit null check)

Thus, whenever using a method inside a conditional statement. Keeping the constant on the left hand side is a good practice.