object==null or null==object?

Jijoy picture Jijoy · Mar 3, 2010 · Viewed 150k times · Source

I heard from somebody that null == object is better than object == null check

eg :

void m1(Object obj ) {
   if(null == obj)  // Is this better than object == null ? Why ?
       return ;
   // Else blah blah
}

Is there any reasons or this is another myth ? Thanks for help.

Answer

Laurence Gonsalves picture Laurence Gonsalves · Mar 3, 2010

This is probably a habit learned from C, to avoid this sort of typo (single = instead of a double ==):

if (object = null) {

The convention of putting the constant on the left side of == isn't really useful in Java since Java requires that the expression in an if evaluate to a boolean value, so unless the constant is a boolean, you'd get a compilation error either way you put the arguments. (and if it is a boolean, you shouldn't be using == anyway...)