Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 528
rozer Avatar asked May 30 '10 11:05

rozer


People also ask

What is the difference between null != Object and object != 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.

What is null != In Java?

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.

Can we write null != In Java?

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.

What is the difference between null and empty object?

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 .


2 Answers

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?
like image 196
polygenelubricants Avatar answered Oct 20 '22 17:10

polygenelubricants


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

like image 42
Tim Lloyd Avatar answered Oct 20 '22 17:10

Tim Lloyd