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?


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.


Because primitive data types in Java are not Objects. You can always use one of the wrapper classes to have an Object. Every of the eight primitive data types has its corresponding wrapper:

  • byte: java.lang.Byte
  • short: java.lang.Short
  • int: java.lang.Integer
  • long: java.lang.Long
  • float: java.lang.Float
  • double: java.lang.Double
  • boolean: java.lang.Boolean
  • char java.lang.Character

If you are interested in the whole structure, you can start here (Primitive Data Types).