permaculture playing cards*
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 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null != x vs. x != null" Watch "null != x vs. x != null" New topic
Author

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
Bartender

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 it...in that case, the test for null has to come first, obviously:
if (x!=null && x.someMethod()>10)...


Rob
SCJP 1.4
Matt Horton
Ranch Hand

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

Joined: Sep 22, 2001
Posts: 2578

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

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: 2578

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
 
wood burning stoves
 
subject: null != x vs. x != null
 
Similar Threads
Integer vs int
== vs = Question
Advice on BigDecimal vs. double
if (x != null) vs in (null != x)
String literal vs new String()