Object null-ness check in Java
Which one is recommended and to be used to check the Object null-ness?
null != Object
开发者_运维百科or
Object != null
and other way
null == Object
or
Object == null
...and is there any difference between them?
(In)equality is commutative, so there is no difference.
Historically the former stems from C to avoid accidentally assigning a value in a conditional statement, however that mostly applies to ==
, not !=
. Also Java requires the condition in a conditional statement to have a boolean value, so the only place where it could go wrong nowadays would be
if (a == false) ...
if you accidentally omit one of the =
. A rare case, I guess (though probably not so much, given what students frequently write in their first two terms). Joonas also points out another (more obscure) case in the comments.
It's always more readable to use
Object != null
because that reads as "the object is not null", which is literally what the condition is. The only case where you want to swap the two is to avoid accidentally using
Object = null
which will return true even though it is not the desired behavior, when you wanted to say
Object == null
but in reality not only do modern tools catch these kinds of mistakes, but wide use of the reverse can actually be an impediment to anyone who has to read the code.
精彩评论