Difference between 'a == null' and 'null == a'

java

Solution

There isn't any.

People will sometimes write `null == a` for historical reasons, because it removes the possibility of a typo-related bug in C. If you were to write:

if (a = NULL) { // note, only single =
  ...

in C, then that would execute the assignment statement `a = NULL`, with the statement's result being the value assigned (ie, NULL). Thus, rather than checking `a`'s value, you set it to be NULL and then checked essentially `if (NULL)`, which is always false. This compiles, but is almost certainly not what you want. And it's all due to a small typo of `=` vs `==`.

If you put the `NULL` first, then `if (NULL = a)` is a compilation error, since you can't assign a value to the constant that NULL represents.

In Java, there's no need for this, since `if (null) {...` doesn't compile. (You can still have the same bug in Java with boolean variables: `if (someBooleanVar = someMethod())`. But that's a relatively rare pattern.)

This style is sometimes referred to as "Yoda conditions," since it's reminiscent of Yoda's quirky speaking style in Star Wars.

Problem

When checking to see if a variable is null, I have seen that the suggested coding style is `if(null == a)`. What is the difference between this and `if(a == null)`?

Original source