I have 2 java statements:
Some people says that second form is better because it helps to avoid NPEs, is it true?
No. These are exactly the same, and there is no risk of NPE here to avoid.
Maybe you confused the example with this situation:
if (myvar.equals("something")) if ("something".equals(myvar))
null, the first form would throw an NPE, since
.equals would be dereferencing a
null value, but the second one works just fine, as the
.equals implementation of
String handles a
null parameter gracefully, returning
false in this example. For this reason, in this example, the 2nd form is generally recommended.
A related argument, which one of these is preferred?
if (myvar == null) if (null == myvar)
Consider the possibility of a typo, writing a single
= instead of
if (myvar = null) if (null = myvar)
myvar is a
Boolean, then the first form will compile, the second form will not. So it may seem that the second form is safer. However, for any other variable type, neither form will compile. And even in the case of a
Boolean, the damage is very limited, because regardless of the value of
myvar, the program will always crash with an NPE when the
if statement is reached, due to unboxing a
Since no test will ever get past this statement, and since you should not release untested code, making such mistake is unrealistic.
In short, the safety benefit is so marginally small that it's practically non-existent, so I don't see a reason to prefer this unusual writing style.
As @Nitek pointed out in a comment, an advantage of adopting the second form could be if you make it a habit, so that when you program in other languages where
myvar = null might compile, you'd be slightly safer, out of your "good habits".
I'd still point out that in many languages comparisons with
null are special, with no possibility of such typo errors. For example in Python,
myvar == None is incorrect, and should be written as
myvar is None, so there's no more
== to mistype.
Strictly speaking, although the
null = myvar writing style will not protect you in all languages, it might protect you in some, so I'd have to admit it seems to be a good habit.