No advantage other than preference of the coder, and who your audience (readers) are.
No advantages. It depends on individual!
object != null
is more readable IMO -- as I read it as object is not null then
....
The only advantage for me is second one makes more sense.
Checking if something is nothing makes more sense than checking if nothing is something.
Well, that's solely my opinion.
The advantage of the first option is that if you accidently leave out the ! then you will get a compile error rather than assign null to object. This is obviously more useful when using ==, where you are more likely to miss an =.
The first one might prevent an eroneous assignment instead of comparison,especially if you do object=null instead of object==null.
That being said I could never bring myself to write
if (3==x)
It just warps the reading.
I think you'll find that's an idiom from C where people used to sometimes mistakenly write:
if (n = 1) { ... }
which was always true (and set n
to 1 as well).
It tends not to be necessary nowadays as compilers will often warn you about using a constant expression in conditionals.
I actually prefer the:
if (n == 1) { ... }
since it seems (to me) to be more natural to compare a variable to a constant.
Using it with !=
is redundant even in C since you will almost never mistakenly write =
when you meant !=
.
No difference in semantics. However, stylistically, I find that saying "is x equals nothing" makes more sense than "is nothing equals x"
Another point in this context is related to the equals method. The equals method - unlike the == operator - is not symmetric. Suppose you want to compare a string variable with a string literal. Then you can write it as either:
a.equals("something")
or
"something".equals(a)
The former will throw a NullPointerException if a == null. The latter will return false.
If you are working in a weekly typeed language like C, JavaScript, then null == object
is better since you will not accidentally do null = object
. Your request is related to null != object
, but it is related when code is re-factored.
I'd rather use the version
object != null
but it is just a preference. Apart from that, I just wish to mention that javac will raise a compilation error if you try to compile
if(object = null)
{
...
}
The if clause must be a boolean
public class A { public static void main(String[] args) { Boolean b = new Boolean("True") ; if(b = null) { System.out.println("A"); } } }
if a programmer mistakenly forget to put ! sign in this case error will not be shown at the compile time and this will be only visible in runtime through null pointer exception. so better to follow the first way(I suppose)