12

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.

Community
  • 1
  • 1
rozer
  • 255
  • 2
  • 3
  • 4
  • 3
    Yoda would use the first version of each, other than that, no difference. The second one however, if the first string was null you would have a party in the error log... – Nick Craver May 30 '10 at 11:55
  • Duplicate: http://stackoverflow.com/questions/271561/why-does-one-often-see-null-variable-instead-of-variable-null-in-c – Martijn Courteaux May 30 '10 at 12:01
  • Duplicate: http://stackoverflow.com/questions/1957836/which-way-is-better-null-object-or-object-null-closed – Martijn Courteaux May 30 '10 at 12:02
  • Weird grammatics "Yoda Conditions" http://stackoverflow.com/questions/2349378?tab=votes&page=1#tab-top – stacker May 30 '10 at 14:05

2 Answers2

29

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("").

Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
6

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

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623