简体   繁体   中英

checking primitive data type for null

below is the primitive data type notional which is of double type as shown below.

private double notional;

now i have to do a null check that wheteher notional is coming as null or not and have to throw the exception if it is coming as null which is below i am doing

 if(item.getNotional() == null  )
                {
                    throw new Exception("Rfgygf");
                }

as shown above this is not correct approach as i can not check primitve type for null check , please advise how can i check notional for null check in java

is there any way now how can i overcome from this shall i convert it into Double type

Primitive data types such as double and int cannot be null. It's like an int cannot be 1.1 .

Which means, you don't need to worry about nullity in primitive data types! They are never null and thus will not throw NullPointerException s. I guess the reason why you have this confusion is that you think a variable without a value must be null. But that is wrong. Consider this class:

public class MyClass { int i; }

And now you create an object of the class:

MyClass obj = new MyClass();

Now you print obj.i . What will it be? It's not null, it's 0 !

All primitive data types have a default value . For instance, The default value of int is 0, the default value of double is 0.0 , which explains why the above obj.i is 0. And what is the default for char ? It's '\\0' !

Just remember that primitive data types cannot be null .

Never

Never

Never

When you say

private double notional;

It is not null , it is 0.0d . Primitive values cannot be null .

JLS-4.12.1. Variables of Primitive Type says (in part)

A variable of a primitive type always holds a primitive value of that exact primitive type.

And null is not a primitive value. The explanation can be found at JLS-4.12.5. Initial Values of Variables which says (in part)

For type double , the default value is positive zero, that is, 0.0d .

A primitive type cannot have a null value. Only reference types can have a null value. When you first declare a double, the value stored inside is a 0. Basically, objects of type double will always store a value. If you don't specify what that value is, it will be a 0.

As the other answers have indicated, primitive data types cannot be null.

I suggest you look at the Optional class as an alternative to using nulls to represent no value. Java 8 includes Optional and there are similar versions in the guava library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM