Reputation: 1579
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
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:
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.)
Upvotes: 59
Reputation: 2178
I would recommend using a Double
not a double as your type then you check against null.
Upvotes: 50
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
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
Reputation:
I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.
Upvotes: -1
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