Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(obj == null) vs (null == obj)?

My boss said I should use null == obj, because it's better than obj == null, but he didn't remember why to do this. Is there any reason for using null == obj?
I feel it somehow... opposite!

After some search on Google, the only thing I found is:

in C, it prevents you accidentally from typing (obj = null) in a conditional structure.

like image 898
Luke Vo Avatar asked Jul 30 '11 14:07

Luke Vo


People also ask

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

What does object == null mean in Java?

A null object refers to an object without any reference or an object defined with neutral/null functionality/behavior. These null objects need to be checked to ensure that they are not null while accessing any member or invoking any methods.

Does null == null in Java?

out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.

Can you say == null in Java?

7. == and != The comparison and not equal to operators are allowed with null in Java.


1 Answers

You can't accidently assign null to obj by typing obj = null instead. However, that's a reminiscence from C times, in java, it is not possible, as the = expression returns the right hand side of the assignment. As null is not a boolean, the compiler will complain.

I would try to explain it to my boss once, demonstrate it. If he still doesn't agree with you, just do it. It's a petty thing to fight about with your boss.

like image 142
Femaref Avatar answered Sep 22 '22 03:09

Femaref