Java 未初始化的 int 与 Integer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3893563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uninitialized int vs Integer
提问by Kevin Zhou
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.
我正在学习 Java 以准备考试,但遇到了未初始化的 int/Integer 值的问题。
class A
{
int x;
Integer y;
static int z;
static Integer z2;
public A(){}
}
Lets say I initialize an object of Class A. A a = new A();
假设我初始化了一个类 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
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/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
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
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.
现在我不想怀疑写考试的人了,但是 x == 0 和 y == null 真值哪个是正确的?非常感谢您对原因的解释,谢谢。
采纳答案by Matthew Flaschen
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)
a.x == 0
- 真,因为 ax 的默认值为 0。a.x == null
- 如前所述,这是一个编译时错误。这遵循第15.21.3 节:“如果无法通过强制转换(第 5.5 节)将任一操作数的类型转换为另一个操作数的类型,则会发生编译时错误。” null 类型不能转换为数字。a.y == 0
- 这会尝试取消装箱a.y,
为 null,因此它会抛出 NullPointerException。与上面的(具有文字空值)不同,编译器不会尝试在编译时确定a.y
为空值。a.y == null
- 再次,true 因为a.y
被初始化为 nulla.z == 0
- 与a.x
(静态除外)相同a.z == null
- 与a.x
(静态除外)相同a.z2 == 0
- 与a.y
(静态除外)相同a.z2 == null
- 与a.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.
交互窗格的问题在于如何实现它取决于 IDE。如果 x 和 y 是局部(未初始化)变量,则最后的所有四个比较都将无法编译。
回答by Stan Kurilin
Java values of simple types such as int/long can't be null so they are initialized by 0.
诸如 int/long 之类的简单类型的 Java 值不能为 null,因此它们被初始化为 0。
回答by pablosaraiva
EDIT: Uninitialized local variables can't be used.
编辑:无法使用未初始化的局部变量。
Besides locals:
除了当地人:
Unitialized int equals 0.
未初始化的 int 等于 0。
Unitialized Integer equals null.
未初始化的整数等于 null。
Integer is an Object. Unitialized objects equals null.
整数是一个对象。未初始化的对象等于 null。
int is a primitive type. The language specs define it's uninitialized value is 0.
int 是一种原始类型。语言规范定义它的未初始化值为 0。
回答by Ishtar
int x;
Integer y;
x == 0; true. because x is initialized to 0 by JVM
x == null; Static Error: Bad type in comparison expression
y == 0; java.lang.NullPointerException
y == null; true, because y is uninitialized
回答by GuruC
All the objects/variables in a class are initialized to default values when an object is instantiated.
当一个对象被实例化时,一个类中的所有对象/变量都被初始化为默认值。
Thats the reason, the variables inside the class have the following values:
这就是原因,类中的变量具有以下值:
int x = 0 //default value (value type)
Integer y = null //default values of any object; here Integer is reference type
... and the rest goes on similarly. Hope my answer is useful!!!
......其余的类似。希望我的回答有用!!!
回答by Nabb
In Java, class (static) variables, instance variables (those in your example), and array components are given default values. Local variables on the other hand must be given values explicitly and do not get default values.
在 Java 中,类(静态)变量、实例变量(在您的示例中)和数组组件被赋予默认值。另一方面,局部变量必须显式给出值并且不获取默认值。
For more detail, see §4.12.5.
有关更多详细信息,请参阅第4.12.5 节。
回答by JeffW
This one has bugged me before since descriptions and behavior seems a little inconsistent. If you look at the language specificationin section 4.12.5there is a section that describes this and does jive with what you observed the compiler doing.
因为描述和行为似乎有点不一致,所以这个问题之前一直困扰着我。如果您查看第 4.12.5 节中的语言规范,则有一节描述了这一点,并且与您观察到的编译器所做的一致。
The reason I think this is confusing at times is that other publications I have read from Sun ("Core Java 2" for example) describe the behavior that your prof indicated. And in another variation, I use NetBeans which allows the use of uninitialized primitives but flags the use of uninitialized objects; I am not sure if that is a compiler or an IDE choice though.
我认为这有时令人困惑的原因是我从 Sun 阅读的其他出版物(例如“Core Java 2”)描述了您的教授指出的行为。在另一个变体中,我使用 NetBeans,它允许使用未初始化的原语,但标记未初始化对象的使用;不过,我不确定这是编译器还是 IDE 选择。
[EDIT : after reviewing one of the posts, I believe that this confusion does stem from the different behavior for local variables vs fields.]
[编辑:在查看其中一篇文章后,我相信这种混淆确实源于局部变量与字段的不同行为。]
回答by Atspulgs
This question was asked a while back, and there are correct answers provided, however, I feel that they can be expanded somewhat.
前阵子问过这个问题,已经给出了正确的答案,但是,我觉得它们可以扩展一些。
I would like to quote a couple a lines from the official tutorials page. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
我想引用官方教程页面中的几行。 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Fields that are declared but not initialized will be set to a reasonable default by the compiler
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. Accessing an uninitialized local variable will result in a compile-time error.
声明但未初始化的字段将由编译器设置为合理的默认值
局部变量略有不同;编译器永远不会为未初始化的局部变量分配默认值。访问未初始化的局部变量将导致编译时错误。
In Java primitives have a value which is a number. (its not quite as simple and I do urge you to read more about it.) A value for an object is a reference from where it is possible to find the contents of the object.
在 Java 原语中有一个值,它是一个数字。(它并不那么简单,我强烈建议您阅读更多相关信息。)对象的值是一个引用,可以从中找到对象的内容。
Default value for a primitive is essentially a 0 where as default value for an object is null. (when uninitialized and when a field)
基元的默认值本质上是 0,而对象的默认值是 null。(未初始化时和字段时)
In your example, you try to compare "0 to 0, null to null and null to 0".
在您的示例中,您尝试比较“0 到 0、null 到 null 和 null 到 0”。
Fact is: null != 0.
事实是:null != 0。
- 0 = a numeric value representing nothing.
- null = a literal for representing non existing reference. (you may see What is null in Java?for more details on null)
- 0 = 一个不代表任何内容的数值。
- null = 用于表示不存在的引用的文字。(您可能会看到Java 中的 null 是什么?有关 null 的更多详细信息)
FYI: I believe this question was answered splendidly by Matthew Flaschen already, I merely wanted to add extra info for those who are interested.
仅供参考:我相信 Matthew Flaschen 已经很好地回答了这个问题,我只是想为感兴趣的人添加额外的信息。
回答by vincent456
class A
{
int x;
Integer y;
static int z;
static Integer z2;
public A(){}
}
your compiler says
你的编译器说
x == 0; true;
x == null; Static Error: Bad type in comparison expression
y == 0; java.lang.NullPointerException
y == null; true
your teacher says
你的老师说
x == 0; Uninitialized
x == null; Undefined
y == 0; java.lang.NullPointerException
y == null; Uninitialized
Both are correct, except your teacher uses different terms. The reason is that by default JAVA initialize uninitialized values to 0 or null for objects. Your teacher refers to them as uninitialized. He is right because these values have not been initialized yet (but they still have default values). Your teacher wants to teach you to always initialize your variables because it's good practice.
两者都是正确的,只是您的老师使用了不同的术语。原因是默认情况下,JAVA 将对象的未初始化值初始化为 0 或 null。您的老师将它们称为未初始化。他是对的,因为这些值尚未初始化(但它们仍然具有默认值)。您的老师想教您始终初始化变量,因为这是一种很好的做法。