开发者

what is the difference between null != object and object!=null [duplicate]

开发者 https://www.devze.com 2023-01-01 19:29 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: which way is better “null != object” or “ object != null”?
This question already has answers here: Closed 12 years ago.

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 != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.

Use whatever is most readable. Usually it's something != null.

Related questions

  • ‘ … != null’ or ‘null != …’ best performance?
0

精彩评论

暂无评论...
验证码 换一张
取 消