未初始化的int与整数 [英] Uninitialized int vs Integer
问题描述
我正在研究我的Java以准备考试,我遇到了一些未初始化的int / Integer值的问题。
I was just studying up on my Java in preparation for an exam and I ran into a sort of problem with uninitialized int/Integer values.
class A
{
int x;
Integer y;
static int z;
static Integer z2;
public A(){}
}
让我说我初始化一个对象A类=新A();
Lets say I initialize an object of Class A. A a = new A();
我在编译器中尝试了这个并得到了结果
I've tried this in a compiler and got the results
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
此外,我在交互窗格中尝试了一些未初始化的int / Interger比较,看看我是否愿意如果我的x,y不是上面的类实例变量,则得到不同的结果。
Furthermore , I tried some more uninitialized int/Interger comparisons in an interactions pane to see if I would get different results if my x, y were not class instance variables as they are above.
int x;
Integer y;
x == 0; true
x == null; Static Error: Bad type in comparison expression
y == 0; java.lang.NullPointerException
y == null; true
然而,我的教授在一次演讲中声称价值观应如下:
However, my professor claims in a lecture that the values should be as follows:
x == 0; Uninitialized
x == null; Undefined
y == 0; java.lang.NullPointerException
y == null; Uninitialized
现在我不想怀疑写考试的人,但是x == 0和y == null真值是否正确?关于为什么会非常感谢的解释,谢谢。
Now I don't want to doubt the one who writes the exam, but which x == 0 and y == null truth value is correct? An explanation on why would be very much appreciated, thank you.
推荐答案
-
ax == 0
- 是的,因为ax的默认值为0. -
ax == null
- 如上所述,这是一个编译时错误。这是从§15.21.3 :如果无法通过转换转换(§5.5)将任一操作数的类型转换为另一个操作数的类型,则会发生编译时错误。 null类型不能转换为数字。 -
ay == 0
- 这会尝试取消装箱ay,
为null,因此抛出NullPointerException。与上面的(有一个文字null)不同,编译器不会试图在编译时弄清楚ay
将为null。 -
ay == null
- 同样,为真,因为ay
初始化为null -
az == 0
- 与ax
相同(静态除外) -
az == null
- 与ax
相同(静态除外) -
a.z2 == 0
- 与相同
(静态除外) -
a.z2 == null
- 与ay
相同(静态除外) a.x == 0
- True because a.x has a default value of 0.a.x == null
- As noted, this is a compile-time error. This follows from §15.21.3: "A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5)." The null type isn't convertible to a number.a.y == 0
- This tries to unboxa.y,
which is null, so it throws a NullPointerException. Unlike the above (which has a literal null), the compiler doesn't try to figure out at compile-time thata.y
will be null.a.y == null
- Again, true becausea.y
is initialized to nulla.z == 0
- Same asa.x
(except static)a.z == null
- Same asa.x
(except static)a.z2 == 0
- Same asa.y
(except static)a.z2 == null
- Same asa.y
(except static)
交互窗格的问题在于IDE如何实现它。如果x和y是本地(未初始化)变量,则所有四个最后比较都将无法编译。
The problem with the interactions pane is that it's up to the IDE how to implement it. If x and y are local (uninitialized) variables, all four of your last comparisons will fail to compile.
这篇关于未初始化的int与整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!