I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null
. This is true for below thing too
"true".equals(x)
.
Why is this so?
I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null
. This is true for below thing too
"true".equals(x)
.
Why is this so?
anything != null
is exactly equivalent to null != anything
.
On the other hand, "true".equals(x)
avoids the need to check if x
is null when doing x.equals("true")
.
The reason for including constants on the left hand side of an equals expression is to avoid NullPointerException
even when the variable is null. This also improves the readability of the expression.
That being said, null!=something
is a personal choice and I would prefer using something!=null
.
These are two separate practices.
Using null
on the left side when comparing to null ensures that you won't, by mistake, use =
instead of ==
. However, this is a practice taken from languages other than Java, as in Java the expression
if ( something = null )
is going to fail as it does not resolve to a boolean value. In other languages it may be permissible to use a condition whose value is actually a pointer.
Thus this practice has no meaning in Java.
The second practice, as you were told, has to do with preventing a NullPointerException
. It should be noted that this practice is controversial, because it allows a null
to propagate to a later point in the program, and that usually means that it will be harder to find when it causes a bug.
That check is so the program ensures the variable in question has been initialized before reading it. If a program tries to access a null variable, it will crash (specifically in Java it will throw a NullPointerException
). It is a critical aspect of defensive programming.
As far as ordering, the evaluation of whether something is null or not is commutative. Meaning:
something != null
Is the same as
null != something
It is all a matter of personal preference. And as @manouti explains above, "true".equals(x)
avoids the need to check if x is null when doing x.equals("true")
, so you save a line of code.
This is called a Yoda condition. Among other things, it helps prevent an accidental assignment due to a missing =
or !
, as in foo = null
. The reverse, null = foo
, would not even compile.
That said, it is purely a stylistic preference. foo != null
is logically equivalent to null != foo
.
Seems that some people prefer null != anything
, because anything
might be quite long expression, so writing null
first makes it visible in the narrow window and simplifies code reading ("ok, we just check if something is not null"). But it's totally a matter of style.
As for "true".equals(x)
, it's well explained by @manouti.