ollaollu
ollaollu

Reputation: 483

came across a null pointer error and I need a clearer understanding why it throws it

was playing around more with java and actual database values and came across an interesting null pointer error well hidden in a working code. So there are 3 variables:

double x = data.getValue1; //this returns 0.0 from database 
double y = data.getValue2; //this returns a null from database
double z = 0; //variable is initialised

double z = x*y; //same as (z = 0.0 * null;) 

now this code will work if x and y return actual values but doesn't work when this values 0.0 and null.

double z is further used in a grand total calculation. Let's say

double grandTotal = z + (another double value) + (another double value);

but double grandTotal will not work because of z.

Now I need an explanation why this happens and how better to handle the situation so that if z or another double value falls in that situation, it doesn't affect grandTotal from summing all it's values

Upvotes: 0

Views: 77

Answers (2)

Paul Richter
Paul Richter

Reputation: 11072

The double type, referred to as a primitive, (the lowercase version, if you will) cannot be null. Primitive values are initialized to a 0.0 (floats and doubles) and 0 (integers, longs, etc).

The object version Double (note the uppercase), can be null. If your getValue2 field is of type Double (as opposed to double), and it is null, and you attempt to assign it to a primitive value, a process called unboxing (as mentioned by August) occurs, and you would end up with Null Pointer Exception (NPE).

Otherwise, however, if getValue2 is in fact a double (note the lowercase), then you'd simply get back 0.0, and normal calculations can proceed normally from there (though perhaps not with the results you were expecting).

As Hovercraft said, simply checking for a null value might be an acceptable solution.

Upvotes: 2

Ankur Singhal
Ankur Singhal

Reputation: 26067

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

If you are getting data via ResultSet.getDouble(), use ResultSet.wasNull().

refer here for more info and this.

Upvotes: 1

Related Questions