115

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.

Raedwald
49.1k49 gold badges161 silver badges249 bronze badges
asked Mar 3, 2010 at 6:37
1

11 Answers 11

160

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

Basil Bourque
345k128 gold badges946 silver badges1.3k bronze badges
answered Mar 3, 2010 at 6:39

Comments

39

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.

answered Mar 3, 2010 at 7:25

Comments

30

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.

answered Mar 3, 2010 at 6:43

1 Comment

For non-Boolean types, the code will not compile because the type of the expression "object = null" will not be boolean. Due to auto-boxing, it will compile for Boolean.
11

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")) {
answered Mar 3, 2010 at 7:28

Comments

9

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
answered Mar 3, 2010 at 6:45

Comments

5

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.

answered Mar 3, 2010 at 6:43

Comments

3

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

answered Mar 3, 2010 at 6:40

1 Comment

nope, Java compiler will catch that kind of typo whatever order you prefer
3

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
answered Mar 3, 2010 at 11:12

Comments

3

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.

Sumit Singh
15.9k6 gold badges63 silver badges90 bronze badges
answered Sep 5, 2012 at 4:06

1 Comment

wonder if you changed the order of the checks if that would have the same result. wonder if this is consistent across all versions of java across all platforms.
3

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.

answered May 8, 2018 at 6:29

Comments

2

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 
answered Jul 30, 2019 at 9:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.