How to check if a double is null?

I would recommend using a Double not a double as your type then you check against null.


A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).

More info on default primitive values here.


Firstly, a Java double cannot be a Java null, and cannot be compared with null. (The double type is a primitive (non-reference) type and primitive types cannot be null.) I'm therefore assuming the following:

  • The "null" you are trying to detect is a NULL stored in the database that you are querying.
  • You are using JDBC to query the database.

If you call ResultSet.getDouble(...), that returns a double not a Double, the documented behavior is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.

Changing the declared type of result to Double instead of double as suggested by Toby's answer will not help. When the database contains NULL, the value assigned to result will be a Double(0.0), not a null.

Here are two options that will work:

  • Use ResultSet.wasNull() to test for a (database) NULL ... immediately after the getDouble(...) call.

  • Use ResultSet.getObject(...), and test for null using ==.

The getObject method will deliver a (non-NULL) value as a Double (assuming that the column type is double). It is documented to return null for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject to deliver.)