Java 内存中到底什么是 null [英] What exactly is null in Java memory
问题描述
如果我声明一些像
String str = null;
- 是否为变量
str
分配了内存? - 如果分配了,会分配多少字节?
- 如果没有分配,JVM怎么知道有一个名为
str
的变量被声明了? - 如果已经分配,如果内存中有
null
值,那么null
的二进制表示究竟是什么? - Is there memory allocated for variable
str
? - If allocated, how many bytes will be allocated?
- If not allocated, how does the JVM know that there is some variable called
str
been declared? - If allocated and if there is
null
value inside the memory, then what exactly is the representation ofnull
in binary?
推荐答案
当您执行以下操作时:
String str = null;
唯一分配的是对字符串的引用(这类似于包含指针类型的语言中的字符串指针).此引用是一个 32 位或 64 位变量(取决于您的硬件架构和 Java 版本),它驻留在堆栈中(可能取决于您的声明所在的确切上下文).
The only thing allocated is a reference to a string (this is analogous to a string-pointer in languages which contain pointer-types). This reference is a 32 or 64 bit variable (depending upon your hardware architecture and Java version) which resides on the stack (probably, depending upon the exact context in which your declaration is placed).
不应为 null
本身分配内存,因为 null
实际上不是有效的对象实例.它只是一个占位符,指示对象引用当前未引用对象.可能它只是字面值 0
,这样将对象引用分配给 null
相当于在 C/中将指针类型设置为 NULL
C++.但最后一点是我的猜测.
No memory should be allocated for the null
itself, because null
is not actually a valid object instance. It is simply a placeholder that indicates that the object reference is not currently referring to an object. Probably it is simply the literal value 0
, such that assigning an object reference to null
is equivalent to setting a pointer type to NULL
in C/C++. But that last bit is conjecture on my part.
这篇关于Java 内存中到底什么是 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!