Java - null变量是否需要内存空间 [英] Java - Does null variable require space in memory
问题描述
class CheckStore {
private String displayText;
private boolean state;
private String meaningfulText;
private URL url;
public CheckStore(String text, boolean state) {
this.displayText = text;
this.state = state;
}
:
:
}
As我在构造函数中只初始化了两个变量( displayText
和 state
),其余两个变量(<$ c) $ c>有意义的文本和 url
其值 null
)将需要空格存储的内存 null
value。
As I am initializing only two variables (displayText
and state
) in the constructor, Will the rest two variables (meaningfulText
and url
which will have the value null
) will require space in memory to store null
value.
Q1。我认为他们需要空间。如果他们愿意,那么 null
值占用内存的内存量(如 int
需要4个字节)。
Q1. I think they will require space. If they will, then how much memory does a null
value takes in the memory (like int
takes 4 bytes).
Q2。字符串占用内存的空间大小。我想这将取决于字符串的长度。那么一个字符串需要多长的空间长度?
Q2. How much space a string takes in memory. I guess it will depend on the length of the string. So how much space a string takes of how much length?
推荐答案
在Java中, null
只是一个引用(基本上是一个受限制的指针)可以拥有的值。这意味着参考没有任何意义。在这种情况下,您仍然占用参考空间。这是32位系统上的4个字节或64位系统上的8个字节。但是,在实际分配该类的实例以指向引用之前,您不会为该引用指向的类占用任何空间。
In Java, null
is just a value that a reference (which is basically a restricted pointer) can have. It means that the reference refers to nothing. In this case you still consume the space for the reference. This is 4 bytes on 32-bit systems or 8 bytes on 64-bit systems. However, you're not consuming any space for the class that the reference points to until you actually allocate an instance of that class to point the reference at.
编辑:As就字符串而言,Java中的字符串
为每个字符占用16位(2字节),加上少量的簿记开销,这可能是未记录的,并且特定于实现。
As far as the String, a String
in Java takes 16 bits (2 bytes) for each character, plus a small amount of book-keeping overhead, which is probably undocumented and implementation specific.
这篇关于Java - null变量是否需要内存空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!