Raysen Jia
Raysen Jia

Reputation: 389

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

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

Upvotes: 12

Views: 4648

Answers (2)

yshavit
yshavit

Reputation: 43391

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.

Upvotes: 35

nanofarad
nanofarad

Reputation: 41271

For a == comparison, none. See JLS for details. For equals, a.equals(null) will invoke the equals method defined in A's class with the parameter null while null.equals(a) would be invalid.

However, you could also consider where one of the sides of the comparison is not necessarily a null value, but is nullable. In that case (notNull and nullable are both local variables or fields of a reference type:

notNull==nullable

is the same as

nullable==notNull

but

notNull.equals(nullable)

should not throw a NullPointerException while nullable.equals(notNull) will throw one if nullable is null.

Upvotes: 1

Related Questions