Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 972
pallasmedia Avatar asked Feb 01 '12 02:02

pallasmedia


People also ask

Can a double be 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.

Is double is null C#?

double can never be null because it is a value type.

Can you check if something equals null?

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 .


2 Answers

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

like image 172
Stephen C Avatar answered Oct 05 '22 23:10

Stephen C


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

like image 22
Toby Samples Avatar answered Oct 05 '22 23:10

Toby Samples