Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes null == someobject Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null == someobject" Watch "null == someobject" New topic

null == someobject

Garlapati Ravi
Ranch Hand

Joined: Mar 05, 2008
Posts: 171
Hi All,

I have seen a code (null == someobject), we can even write this as (someobject == null), to check whether object is null or not.

what is the advantage of (null == someobject) over (someobject == null)

Ravi Kumar

Ravi Kumar
SCWCD 5 - 89%, SCJP 1.4 - 90%
Vikas Kapoor
Ranch Hand

Joined: Aug 16, 2007
Posts: 1374
Hello Garla,

In both the cases it will evaluate the object reference and see if it is referencing to any object or not.

I don't know if one is better than other in someway.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

something == null will be turned into an assignment if you forget one =. Now usually you would get a compiler error stating that the expression is not boolean, but if something is declared to be Boolean, auto unboxing will turn it into a boolean and it will compile just fine. It won't run though, since the unboxing will throw a NullPointerException.

If you use null == something, it will always be a compiler error if you forget one =. You can't assign anything to any literal, including null.

I prefer something == null though - if you test properly these kinds of errors will be quite clear.

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46344
The idiom (null == something) [or (3 == something)] is more useful in C and C++ where you can use 1=true and 0=false.

[edit]For 1=true read "1 means true" and for 0=false read "0 means false."[/edit[
[ June 06, 2008: Message edited by: Campbell Ritchie ]
I agree. Here's the link:
subject: null == someobject
It's not a secret anymore!