为什么原始数据类型不能为“null”。在Java? [英] Why can't primitive data types be "null" in Java?
问题描述
当声明任何原始类型数据(如 int
或 double
)时,它们会初始化为 0
或 0.0
。为什么我们不能将它们设置为 null
?
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;
在这种情况下, object
只是一个指向其值为3的Integer对象的指针。也就是说,在存储变量对象的内存位置,您所拥有的只是对数据实际位置的引用。另一方面,存储 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.
所以,你可以将对象
设置为null,但这只是意味着该对象的数据为空(即未分配)。你不能将int设置为null,因为语言会将其解释为值0。
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.
希望有帮助!
这篇关于为什么原始数据类型不能为“null”。在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!