Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null != x vs. x != null

 
Matt Horton
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is there a benefit to checking for nulls before the operator vs. after an operator? I remember an argument between friends a few years ago (Sudhir, Kashif I know you're reading ) but I never found out if it was true or not.
Is there anything to it?
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, just a matter of style. I prefer x !=null than the other way...null != x seems awkward to me, but it's technically ok.
The only issue I can think of concerning ordering is when you are checking a reference for null before you make a method call on it...in that case, the test for null has to come first, obviously:
if (x!=null && x.someMethod()>10)...
 
Matt Horton
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob!
 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you are checking for equality, it is a good practice to have a literal or constant on the LHS such as -
if(null == objRef)
or
if(1 == iTotalRec)
as it avoids a common mistake of assigning in the if statement such as -
if(iTotalRec = 1) // 1
as compared to
if(1 = iTotalRec) // 2
here in case 2, the compiler will flag an error, saving you from debugging trouble later on.
It does look a bit starnge unless you are used to it, but it's extremely helpful, allowing the compiler to flag it for you instead of you hunting for it later while debugging.
HTH,
- Manish
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler will flag an error for case 1 too - give it a try. Non-boolean expressions will cuse errors if used in conditional statements, regardless of which element is on LHS or RHS. The only time this doesn't work is if the type of LHS and RHS is boolean:

Oops! This evaluates to true always, because expression is assigned to true. So it's still something to beware of, but much less often than in C/C++. (Which might make it more dangerous, because you aren't expecting it when it happens.)
 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah right!
In Java, it will flag error for any non-boolean expression, just slipped out of my mind. Got this habbit from C/C++ programming, but a good practice anyways.
Thanks for correcting me,
- Manish
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic