Checking for null - what order? [duplicate]

When checking for nulls I use this:

String str;

if(str == null){
    //...
}

but I've seen this as well:

if(null == str){
    //...
}

Is there any advantage of using one over the other? Or is it just to improve readability?


Solution 1:

The second version ( null == str ) is called a yoda condition.

They both result in the same behavior, but the second one has one advantage: It prevents you from accidentally changing a variable, when you forget one =. In that case the compiler returns an error at that row and you're not left with some weird behavior of your code and the resulting debugging.

Solution 2:

The null == x convention is usually found in code written by people familiar with C, where an assignment can also be an expression. Some C programmers write code like this so that if they miss an = in

if (NULL == ptr)...

the code will not compile, since NULL = ptr is not a valid assignment. This prevents a rather sneaky error from being introduced in the code-base, although modern C compilers make make such conventions obsolete, as long as one takes care to enable and read the generated warnings...

This coding style has never had any usefulness in Java, where reference assignments cannot be used as boolean expressions. It could even be considered counter-intuitive; in their natural language most people will say "if X is null...", or "if X is equal to 17...", rather than "if null is equal to X...".

Solution 3:

There's no difference between the two other than readability. Use whichever makes more sense to you.

Solution 4:

As you stated readability is the most important reason. Reading it out loud, the (null == str) does not read well. It's almost like reading right to left. (str == null) reads much better.

In addition, I think the following needs to be taken into consideration:

if (str != null)  
if (str == null)

vs.

if (null != str)
if (null == str)

I would expect the positive (str == null) and the negative to be written in the same manner, which is another reason I would favor the top set.

Solution 5:

if (null == str) {
}

is a programming idiom from c/c++, where the assignment operator = can be used to resolve to a true/false statement. For example in c if you want to check if I can open a stream in c/c++, you can

if (myStream = openStream())

which sets opens and assigns in one line. However, this means that people often type = when they mean ==, and it would be valid syntax in c: for example if (x = 5) will always resolve to true, when they really mean if (x ==5). So people write if (5 == x) so if you leave out a = your code won't compile.

This doesn't apply to java.