This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
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)...
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
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.)
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