This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes null != x vs. x != null Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null != x vs. x != null" Watch "null != x vs. x != null" New topic

null != x vs. x != null

Matt Horton
Ranch Hand

Joined: Feb 06, 2002
Posts: 107
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

Joined: Jan 07, 2002
Posts: 2205
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 that case, the test for null has to come first, obviously:
if (x!=null && x.someMethod()>10)...

SCJP 1.4
Matt Horton
Ranch Hand

Joined: Feb 06, 2002
Posts: 107
Thanks Rob!
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

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)
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.
- Manish
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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.)

"I'm not back." - Bill Harding, Twister
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

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
I agree. Here's the link:
subject: null != x vs. x != null
jQuery in Action, 3rd edition