File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes obj == null OR null == obj, which is better? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "obj == null OR null == obj, which is better?" Watch "obj == null OR null == obj, which is better?" New topic
Author

obj == null OR null == obj, which is better?

Mohit Jain
Ranch Hand

Joined: Jun 04, 2007
Posts: 74
While comparing a reference for null value, out of following two ways which way is better??

obj == null OR null == obj

They say it doesnt make difference when this condition is used all alone, but its better to put null on left side when two conditions are concatenated using && or || like -

null == obj && <some condition>


Please suggest.


SCJP 5.0, SCWCD in progress
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Please be patient.


[My Blog]
All roads lead to JavaRanch
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19073
    
  40

For C/C++, if you accidentally used "=" (assignment) instead of "==" (comparison), it will assign the value, and still have a valie that can be used in the condition. Thia made for some really obscure bugs. Reversing it fixed the problem, as you can assign a variable to a literal (null).

For Java, it doesn't matter as you can't use null as a boolean (implicitedly).

Henry
[ April 25, 2008: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: obj == null OR null == obj, which is better?