object==null or null==object?

JavaNull

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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...)

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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")) {

Solution 6 - Java

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.

Solution 7 - Java

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 ==.

Solution 8 - Java

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

Solution 9 - Java

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.

Solution 10 - Java

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.

Solution 11 - Java

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 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJijoyView Question on Stackoverflow
Solution 1 - JavaLaurence GonsalvesView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaChandra SekarView Answer on Stackoverflow
Solution 4 - JavaR Samuel KlatchkoView Answer on Stackoverflow
Solution 5 - JavacherouvimView Answer on Stackoverflow
Solution 6 - JavavavaView Answer on Stackoverflow
Solution 7 - JavaIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 8 - JavaSPeeView Answer on Stackoverflow
Solution 9 - JavaAvinashView Answer on Stackoverflow
Solution 10 - JavaBenny BottemaView Answer on Stackoverflow
Solution 11 - JavaTanmay NaikView Answer on Stackoverflow