*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null == someobject" Watch "null == someobject" New topic
Author

null == someobject

Garlapati Ravi
Ranch Hand

Joined: Mar 05, 2008
Posts: 168
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)

Regards,
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
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38046
    
  22
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: http://aspose.com/file-tools
 
subject: null == someobject
 
Similar Threads
What is the difference between "someObject == null" and "null == someObject".
rendered problem
string conversions?!?
A question on Garbage Collection- Can any one explain
What happens?