I have been going through some site where they talk about how to prevent NPE. There I saw people say use null != object
but I don't understand why. What is the difference between doing the below in java?
if(null != object)
vs
if(object != null)
There is no difference between the two in the effect.
However there is a school of thinking where it is recommended to use un-assignable (constant) values on the left hand side of a operator. Because this reduces the risk of unintended assignment (this is from the time where C compilers have been not warning about it).
// this is dangerous when misstyped
if (object = null) {
The argument that writing the null first really reduces the effect of misstyping is however pretty weak. Especially when not using "==" but "!=" or "<". So I would say, ignore those recommendations.
There are however some situations where order is helpfull to prevent NPE:
if ("string".equals(object))
In this case you dont get an NPE when "object" is null.
What is the difference between doing the below in java?
There is no difference in terms of what the code means.
There is no difference in terms of code safety / robustness.
In some languages, the if (null == object)
pattern helps to avoid this mistake:
if (object = null)
... which accidentally trashes the value of the object
variable.
But in Java, an if
statement requires a condition expression whose type is boolean
, and the type of object == null
is NOT boolean. Hence that particular mistake / typo is guaranteed to give a compilation error.
Digression ...
The case where you plausibly could get into trouble with '==' versus '=' in classic Java is this:
if (flag == true)
or
if (flag == false)
However, no experienced Java programmer would write that. Instead they would write:
if (flag)
and
if (!flag)
With Java 5 and onwards, autoboxing of Boolean
can get you into trouble. However, in that case you are doing something that is inadvisable anyway. Consider this:
Boolean TRUE = true;
Boolean TOO_TRUE = new Boolean(true); // generates a new instance ...
if (TRUE == TOO_TRUE) { // should be TRUE.equals(TRUE)
....
}
Again, an experienced programmer would avoid using boxed types unnecessarily, and avoid testing them with ==
. Besides, you would probably get a warning for this from an IDE or from a static anaylser like FindBugs or PMD.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.