Possible Duplicates:
which way is better “null != object” or “ object != null”?
Why does one often see “null != variable” instead of “variable != null” in C#?
‘ … != null’ or ‘null != …’ best performance?
Please guide me.
what is the difference between null != object and object!=null
same for "".equal("something") and "something".equals("")
which one is good for processing.
The first two are equivalent, but the "null != object" is an old practice from languages where it is valid to write "if (object = null)" and accidentally assign null to the object. It is a guard to stop this accident from happening.
It is a literal similar to the true and false. In Java, null is a keyword much like the other keywords public, static or final. It is just a value that shows that the object is referring to nothing.
null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can't write NULL or 0 as in C language.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
There is absolutely no difference in either semantics or performance.
The ==
in this case is a reference inequality operation; it can never throw NullPointerException
.
JLS 15.21.3 Reference Equality Operators == and !=
If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.
The result of
!=
isfalse
if the operand values are bothnull
or both refer to the same object or array; otherwise, the result istrue
.
Use whatever is most readable. Usually it's something != null
.
The first two are equivalent, but the "null != object" is an old practice from languages where it is valid to write "if (object = null)" and accidentally assign null to the object. It is a guard to stop this accident from happening.
The second whilst equivalent has the added advantage that if "something" is null you will not get a null reference exception whereas you would if you did: something".equals("").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With