Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

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?

0
c0upal
Asked:
c0upal
1 Solution
 
objectsCommented:
something like:
if (a!=null && b!=null && a.equals(b))  

though it may depend on your requirements.
0
 
objectsCommented:
Or if you want to consider two nulls as equal then:

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

0
 
jaquoCommented:
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
}


0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
helloknsCommented:
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
0
 
objectsCommented:
> u will not get nullpointer exception

Not necessarily.
That depends on the implementation of the equals() method of b's class.
0
 
CleanupPingCommented:
c0upal:
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 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now