我刚刚学习 Java 以准备考试,但遇到了未初始化 int/Integer 值的问题。
class A
{
int x;
Integer y;
static int z;
static Integer z2;
public A(){}
}
假设我初始化了一个 A 类的对象。A a = new A();
我已经在编译器中尝试过这个并得到了结果
a.x == 0; true
a.x == null; Static Error: Bad type in comparison expression
a.y == 0; java.lang.NullPointerException
a.y == null; true
a.z == 0; true
a.z == null; Static Error: Bad type in comparison expression
a.z2 == 0; NullPointerException
a.z2 == null; true
此外,我在交互 Pane 中尝试了一些未初始化的 int/Interger 比较,以查看如果我的 x、y 不是上面的类实例变量,我是否会得到不同的结果。
int x;
Integer y;
x == 0; true
x == null; Static Error: Bad type in comparison expression
y == 0; java.lang.NullPointerException
y == null; true
但是,我的教授在一次讲座中声称这些值应该如下:
x == 0; Uninitialized
x == null; Undefined
y == 0; java.lang.NullPointerException
y == null; Uninitialized
现在我不想怀疑写考试的人,但是哪个 x == 0 和 y == null 真值是正确的?非常感谢您解释原因,谢谢。
最佳答案
a.x == 0
- 正确,因为 a.x 的默认值为 0。a.x == null
- 如前所述,这是一个编译时错误。这来自 §15.21.3 :“如果无法通过强制转换(第 5.5 节)将任一操作数的类型转换为另一个操作数的类型,则会发生编译时错误。” null 类型不能转换为数字。a.y == 0
- 这会尝试对 null 的a.y,
进行拆箱,因此它会抛出 NullPointerException。与上面的(有一个字面值 null)不同,编译器不会在编译时试图找出a.y
将为 null。a.y == null
- 再次验证,因为a.y
已初始化为 nulla.z == 0
- 与a.x
相同(静态除外)a.z == null
- 与a.x
相同(静态除外)a.z2 == 0
- 与a.y
相同(静态除外)a.z2 == null
- 与a.y
相同(静态除外)
交互 Pane 的问题在于如何实现它取决于 IDE。如果 x 和 y 是本地(未初始化)变量,那么您最后的四个比较都将无法编译。
关于java - 未初始化的 int 与 Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3893563/