object==null or null==object?
Solution 1:
This is probably a habit learned from C, to avoid this sort of typo (single =
instead of a double ==
):
if (object = null) {
The convention of putting the constant on the left side of ==
isn't really useful in Java since Java requires that the expression in an if
evaluate to a boolean
value, so unless the constant is a boolean
, you'd get a compilation error either way you put the arguments. (and if it is a boolean, you shouldn't be using ==
anyway...)
Solution 2:
As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean
(which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)
What hasn't been mentioned is that many people (myself certainly included) find the if (variable == constant)
form to be more readable - it's a more natural way of expressing yourself. This is a reason not to blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.
Solution 3:
This is not of much value in Java (1.5+) except when the type of object is Boolean
. In which case, this can still be handy.
if (object = null)
will not cause compilation failure in Java 1.5+ if object is Boolean
but would throw a NullPointerException
at runtime.
Solution 4:
In Java there is no good reason.
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
if (o = null)
will not compile.
The only time this could matter in Java is if the variable is boolean:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality