File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Win a copy of
OCM Java EE 6 Enterprise Architect Exam Guide
this week in the
Switching order for equals operator
Joined: Dec 07, 2009
Dec 07, 2009 06:12:02
I've seen in several places that a way to avoid null pointer exceptions is to switch the order of the equals operator. For example, using
Although this seems like a good idea, doesn't this make it harder to debug down the line if you run into problems? Isn't is basically hiding the fact that you have a NPE where you shouldn't?
Just curious what your thoughts were.
Joined: Oct 27, 2005
Dec 07, 2009 06:32:07
In my opinion, you should only write this code if otherwise you would have written
if (dog != null && dog.equals("Jack"))
In other words, if you already intended to have the null check in place.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions
How To Answer Questions
Joined: Oct 13, 2005
Dec 07, 2009 07:19:26
If there is any chance of "dog" being
, then dog.equals("Fido") will throw an Exception and "Fido".equals(dog) will not throw an Exception.
Joined: Sep 12, 2007
Dec 07, 2009 07:32:05
General Practice is this only that Rob has suggested.
1. if (dog != null && dog.equals("Jack"))
It is sorta covered in the
JavaRanch Style Guide
subject: Switching order for equals operator
Do we need to override the hashCode() method ?
Help on ==
JSP with a if-statment problem
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014