我已经搜索了 Internet,但没有找到对我的问题满意的答案。在本地化实例中,如果我有代码:
public static void main (String args[])
{
int x;
System.out.println(x);
}
...它不会编译,因为 Java 编译器会警告我应该初始化 x。我明白这一点。
我的问题是,Java 真的会为整数 x 留出 4 个字节的内存吗?如果是这样,它会清除那 block 内存吗?它是否将其定义为 NULL(我不这么认为,因为 NULL 和 int 是不兼容的类型)?或者 int x
的内存地址是否仍然保留最后存储在内存中的值,或者 x
只是简单地“没有值”?
我知道上面的代码在 C 中有效,而在 C 中,它只会打印出内存块中的任何内容。我想知道 Java 如何处理这个问题。
===编辑===
好的,好的。出于某种原因,我的编程基础知识已经完全从我的脑海中消失了,因为当一个程序无法编译时,内存分配的问题是无关紧要的,正如发布答案的两位成员所指出的那样。 (提示捂脸)
如果我有代码怎么办:
public static void main (String args[])
{
int x;
}
那么整数x
是如何在内存中解析的呢?
最佳答案
这不是警告;这是一个编译器错误。该代码不会编译,因此不会生成字节码。是否预留内存的问题无关紧要,因为没有程序可以运行。
但是,如果 x
变量不是本地变量,则 Java 将分配默认值 0
。
Every variable in a program must have a value before its value is used:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.
Each method parameter (§8.4.1) is initialized to the corresponding argument value provided by the invoker of the method (§15.12).
Each constructor parameter (§8.8.1) is initialized to the corresponding argument value provided by a class instance creation expression (§15.9) or explicit constructor invocation (§8.8.7).
An exception parameter (§14.20) is initialized to the thrown object representing the exception (§11.3, §14.18).
A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).
关于java - Java 中的默认原始值 - 内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26411980/