Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

null == someobject

 
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 21775
103
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 65063
247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!