Pallas
Pallas

Reputation: 1579

How to check if a double is null?

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?

Upvotes: 53

Views: 275379

Answers (6)

Stephen C
Stephen C

Reputation: 718788

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:

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.)

Upvotes: 59

Toby Samples
Toby Samples

Reputation: 2178

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

Upvotes: 50

RAY
RAY

Reputation: 7100

How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull().

Upvotes: 3

onit
onit

Reputation: 6366

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.

Upvotes: 8

user1181445
user1181445

Reputation:

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.

Upvotes: -1

danben
danben

Reputation: 83250

To say that something "is null" means that it is a reference to the null value. Primitives (int, double, float, etc) are by definition not reference types, so they cannot have null values. You will need to find out what your database wrapper will do in this case.

Upvotes: 6

Related Questions