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
?
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!