Reputation: 41193
Sometimes, I see this:
if (a.equals(b)) do(something);
However, if a
is null, a NullPointerException is thrown. Assuming when a==null
and b==null
or if just a==b
that I would want to do(something)
. What's the simplest way to do this check without getting an exception?
Upvotes: 10
Views: 7437
Reputation: 108899
if( a==b || (a!=null && a.equals(b)) )
(The a==b
handles the case when both are null.)
Also be aware of the Java 7 and above Object.equals method:
if(java.util.Object.equals(a, b))
Upvotes: 22
Reputation: 533530
Another way of writing it.
if (a == null ? b == null : a.equals(b))
Upvotes: 24