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.
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("").
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
.
Related questions
- ‘ … != null’ or ‘null != …’ best performance?
精彩评论