How to check if a double is null?

pallasmedia picture pallasmedia · Feb 1, 2012 · Viewed 180.8k times · Source

I'm querying a database and some of the results I'm getting are null. I'm setting these values to a variable with a datatype of double. Let's call the variable "results". So I tried setting up an if statement to see it equals Null which of course didn't work. Here is the code I have for that if statement:

if (results == null)
{
     results = 0;
}

The error I get with this code is:

The operator == is undefined for the argument type(s) double, null

Is there a better way to determine if it's null?

Answer

Stephen C picture Stephen C · Feb 1, 2012

Firstly, a Java double cannot be null, and cannot be compared with a Java null. (The double type is a primitive (non-reference) type and primitive types cannot be null.)

Next, if you call ResultSet.getDouble(...), that returns a double not a Double, the documented behaviour 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.

So your options are:

The getObject method will deliver the value as a Double (assuming that the column type is double), and 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.)