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
?
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.
Primitive data types cannot be null . Only Object data types can be null .
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.
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 .
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!
Because null is a reference. And primitive types are not reference types. Only objects are reference types.
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