In the Java programming language, the two expressions if (object == null)
versus if (null == object)
do exactly the same thing, because the ==
operator is commutative. The former notation is considered more natural when spoken in English, whereas the latter notation has some proponents.
If the programmer mistypes =
for ==
, like if (object = null)
, this is a compile-time error in Java because the condition expression must be a boolean
value, not Object
. Hence, if (object == null)
and if (null == object)
are equally secure against typos in Java.
But in C and C++, integer, floating-point, and pointer types are implicitly coerced to bool
in a condition expression. Writing if (object = null)
will compile but do the wrong thing, whereas writing if (null = object)
should trigger a compile-time error.
See also: https://coderanch.com/t/489740/java/difference-null-object-object-null