comparing two objects that have null values

is there away to use the .equals(function) when the calling object has a possibility that it would be null?

i.e.  if(a..equals(b))  //what if a = null;

as you know this will produce a NullPointerException.. but can is there another way to go around this?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

something like:
if (a!=null && b!=null && a.equals(b))  

though it may depend on your requirements.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Or if you want to consider two nulls as equal then:

if ((a==null && b==null) || (a!=null && b!=null && a.equals(b)))  

Yeah, basically just test if the value that could possibly be null actually IS null before trying a compare.  Then you could add an else statement to handle it from there.

If (a != null) {
  if (a.equals(b))
    //what it is you want to do
else {
  //what to do it a is null

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Another simple solution can be helpful if you are sure that b is always not null, then have the statement like this,

if(b.equals(a)) {

In this case, even if a is null, u will not get nullpointer exception
> u will not get nullpointer exception

Not necessarily.
That depends on the implementation of the equals() method of b's class.
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
Post your closing recommendations!  No comment means you don't care.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.