19

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?

Pokechu22
  • 4,984
  • 9
  • 37
  • 62
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • If you use this to guard against null parameters, [`T Objects.requireNonNull(T[, String])`](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html) might be of your interest. – Philipp Reichart Jun 11 '12 at 16:05
  • it does make a diff (in Java) if checking for boolean conditions to protect against human error of typing something like if(value = true) when you meant if(value == true). Easily done and hard to track down bugs can result from this kind of stuff! – Dori Oct 29 '13 at 15:53

8 Answers8

41

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.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 8
    It depends. As user thkala points out correctly, in Java it doesn't matter. In C it does, however, modern compilers such as LLVM's Clang warn you about this with a "Using the result of an assignment as a condition without parentheses". – Raphael Schaad Jun 19 '13 at 18:45
  • Thanks Sirko, it makes sense to me :) – Ashish Burnwal Oct 14 '17 at 09:44
38

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

thkala
  • 84,049
  • 23
  • 157
  • 201
  • *This coding style has never had any usefulness in Java* imagine that `boolean b=... if (b=isXXX()){...}` and compare to `boolean b=... if (isXXX()==b){}` – bestsss Jun 18 '12 at 08:37
  • @bestsss: I edited my answer to clarify this point. That said, your second snippet could very well be more intuitive than the first in some contexts, depending on whether `b` can be deemed a local constant. `if (false == myFlag)...` is not quite the same though... – thkala Jun 18 '12 at 09:31
  • point is that in the 1st snippet if equivalent of `boolean b;... b=isXXX(); if (b){...}` which is valid, but it can be a mistake as well. For example `boolean b=isYYY(); if (b=isXXX()){}` which doesn't compare `isYYY() to isXXX()` - indeed java it's less prone to the same mistake in C but still possible. – bestsss Jun 18 '12 at 09:44
  • @bestsss: agreed, `if (b == false)...` is valid code and a Yoda-style condition could indeed prevent an error here. That does not make it any more clear or maintainable, though... – thkala Jun 18 '12 at 10:23
4

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

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • 1
    Indeed. Although I can add that I've never seen anyone use the 'null == str' variety, so I'd recommend using the first version because it's simply more conventional. – AardvarkSoup Jun 11 '12 at 15:58
  • The latter sounds like a Yoda condition. – Louis Wasserman Jun 11 '12 at 15:59
  • 3
    Wasn't this also used back in the day to mitigate issues with using a single `=` instead of `==`? `if (str=null)` is valid, but `if (null =str)` isn't. – Mike Park Jun 11 '12 at 15:59
  • 1
    @climbage Yes, but in Java only boolean expressions can be used in if statements, so there's really no difference here. – Jeffrey Jun 11 '12 at 16:00
  • @Jeffrey Right, I just figured it might help explain why you would every see the expression in that order in the first place. – Mike Park Jun 11 '12 at 16:02
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.

tjg184
  • 4,508
  • 1
  • 27
  • 54
2

if(a==b) {} is the same as if(b==a) {} , and the same is true if b was null. It's just a style/order difference as far as functionality, at least in java.

Fewfre
  • 1,461
  • 3
  • 19
  • 32
2
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.

Hans Z
  • 4,664
  • 2
  • 27
  • 50
2

There is no real difference. However the second is considered less error prone. In the first case you would not get an error if you tried to do

String str;

if(str = null){
}

which is something you usually don't do in conditionals.

Also, you get to think about the actual condition first, which is a good practice.

ozon
  • 25
  • 4
  • 1
    You do in fact get an error in Java: Error, incompatible types. Found java.lang.String Required boolean. – TheIT Feb 27 '15 at 01:18
1

Some developers argue that var == null is more error-prone than null == var. Their argument is that you might accidentally assign the variable instead of doing a null-check.

But only when the variable you test against null is a Boolean you can accidentally use the = instead of == and it will compile.

Boolean checked = Boolean.TRUE;
if(checked = null){ // accidentally assigned null and compiles
}

Only in this case the assignment compiles, because the conditional expression must evaluate to a boolean value. See JLS-14.9. Since the assignment expression itself evaluates to a boolean type, it compiles. But you will get a NullPointerException at runtume, because java will try to unbox the checked variable which is null.

If you use any other type then Boolean you will get a compiler error. E.g.

String str = "hello";
if(str = null){ // compiler error, because str = null doesn't evaluate to a boolean
}

My conclusion is that error situations are extremly rare and you can easily write unit tests that detect such errors.

So write the if-statement it in the way it is more readable.

I think "if name is null" makes more sense then "if null is name".

René Link
  • 48,224
  • 13
  • 108
  • 140