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?
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
double can never be null because it is a value type.
The expression obj. equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .
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:
use ResultSet.wasNull()
to test for a (database) NULL ... immediately after the getDouble(...)
call, or
use ResultSet.getObject(...)
, and type cast the result to Double
.
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.)
I would recommend using a Double
not a double as your type then you check against null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With