Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't primitive data types be "null" in Java?

When declaring any primitive type data like int or double they get initialized to 0 or 0.0. Why can we not set them to null?

like image 752
MBMJ Avatar asked Jun 15 '12 08:06

MBMJ


People also ask

Can you set primitive type to 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.

Can primitive long be null Java?

Primitive data types cannot be null . Only Object data types can be null .

Why Java does not support primitive data types?

The primitive types represent single values—not complex objects. Although Java is otherwise completely object-oriented, the primitive types are not. They are analogous to the simple types found in most other non–object-oriented languages. The reason for this is efficiency.

How do you know if a primitive is null?

Primitive values cannot be null . A variable of a primitive type always holds a primitive value of that exact primitive type. For type double , the default value is positive zero, that is, 0.0d .


2 Answers

A primitive type is just data. What we call objects, on the other hand, are just pointers to where the data is stored. For example:

Integer object = new Integer(3); int number = 3; 

In this case, object is just a pointer to an Integer object whose value happens to be 3. That is, at the memory position where the variable object is stored, all you have is a reference to where the data really is. The memory position where number is stored, on the other hand, contains the value 3 directly.

So, you could set the object to null, but that would just mean that the data of that object is in null (that is, not assigned). You cannot set an int to null, because the language would interpret that as being the value 0.

Hope that helps!

like image 153
Miquel Avatar answered Sep 26 '22 01:09

Miquel


Because null is a reference. And primitive types are not reference types. Only objects are reference types.

like image 45
StandByUkraine Avatar answered Sep 26 '22 01:09

StandByUkraine