[java] object==null or null==object?

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.

This question is related to java null

The answer is


Because of its commutative property, the only difference between object == null and null == object (the Yoda version) is of cognitive nature: how the code is read and digested by the reader. I don't know the definitive answer though, but I do know I personally prefer comparing the object I'm inspecting to something else, rather than comparing something else to the object I'm inspecting, if that makes any sense. Start with the subject, then the value to compare it to.

In some other languages this comparison style is more useful.

To safe guard against a missing "=" sign in general though, I think writing null == object is a misguided act of defensive programming. The better way around this particular code is by guaranteeing the behavior with a junit test. Remember, the possible mistake of missing an "=" is not dependant on the method's input arguments - you are not dependent on the right use of this API by other people - so a junit test is perfect to safe guard against that instead. Anyway you will want to write junit tests to verify the behavior; a missing "=" naturally falls within scope.


This is not of much value in Java (1.5+) except when the type of object is Boolean. In which case, this can still be handy.

if (object = null) will not cause compilation failure in Java 1.5+ if object is Boolean but would throw a NullPointerException at runtime.


This trick supposed to prevent v = null kind of typos.

But Java allows only boolean expressions as if() conditions so that trick does not make much sense, compiler will find those typos anyway.

It is still valuable trick for C/C++ code though.


This also closely relates to:

if ("foo".equals(bar)) {

which is convenient if you don't want to deal with NPEs:

if (bar!=null && bar.equals("foo")) {

For the same reason you do it in C; assignment is an expression, so you put the literal on the left so that you can't overwrite it if you accidentally use = instead of ==.


That is for people who prefer to have the constant on the left side. In most cases having the constant on the left side will prevent NullPointerException to be thrown (or having another nullcheck). For example the String method equals does also a null check. Having the constant on the left, will keep you from writing the additional check. Which, in another way is also performed later. Having the null value on the left is just being consistent.

like:

 String b = null;
 "constant".equals(b);  // result to false
 b.equals("constant");  // NullPointerException
 b != null && b.equals("constant");  // result to false

It is Yoda condition writing in different manner

In java

String myString = null;
if (myString.equals("foobar")) { /* ... */ } //Will give u null pointer

yoda condition

String myString = null;
if ("foobar".equals(myString)) { /* ... */ } // will be false 

In Java there is no good reason.

A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:

if (o = null)

will not compile.

The only time this could matter in Java is if the variable is boolean:

int m1(boolean x)
{
    if (x = true)  // oops, assignment instead of equality

As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean (which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)

What hasn't been mentioned is that many people (myself certainly included) find the if (variable == constant) form to be more readable - it's a more natural way of expressing yourself. This is a reason not to blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.


Compare with the following code:

    String pingResult = "asd";
    long s = System.nanoTime ( );
    if ( null != pingResult )
    {
        System.out.println ( "null != pingResult" );
    }
    long e = System.nanoTime ( );
    System.out.println ( e - s );

    long s1 = System.nanoTime ( );
    if ( pingResult != null )
    {
        System.out.println ( "pingResult != null" );
    }
    long e1 = System.nanoTime ( );
    System.out.println ( e1 - s1 );

Output (After multiple executions):

null != pingResult
325737
pingResult != null
47027

Therefore, pingResult != null is the winner.