KaliMa KaliMa - 1 month ago 17
Java Question

Testing for equality with Doubles

In Java, the upper case Double can be null.

However if I have Doubles

a
and
b
and I do this:

if (a.equals(b))


it crashes if one of them is null. Is there a better way to compare them?

Answer

The simplest way in Java 7+ is:

Objects.equals(a, b)

If you are using an earlier version of Java, you can use the conditional operator:

(a != null) ? a.equals(b) : (b == null)