为什么在NullPointerException中使用默认值的Java Integer结果? [英] Why does using a default-valued Java Integer result in a NullPointerException?
问题描述
我是Java新手。我刚刚读到Java中的类变量有默认值。
I am new to Java. I just read that class variables in Java have default value.
我尝试了以下程序,并希望输出为 0
,这是整数的默认值,但我得到 NullPointerException
。
I tried the following program and was expecting to get the output as 0
, which is the default value on an integer, but I get the NullPointerException
.
什么是我错过了?
class Test{
static Integer iVar;
public static void main(String...args) {
System.out.println(iVar.intValue());
}
}
推荐答案
你是的,Java中未初始化的类变量具有分配给它们的默认值。 Java中的 Integer
类型与 int
不同。 Integer
是包装类,它在对象中包装基本类型 int
的值。
You are right, uninitialized class variables in Java have default value assigned to them. Integer
type in Java are not same as int
. Integer
is the wrapper class which wraps the value of primitive type int
in an object.
在您的情况下 iVar
是对整数的引用
尚未初始化的对象。未初始化的引用获取默认值 null
,当您尝试在空引用上应用 intValue
()方法时得到 NullPointerException
。
In your case iVar
is a reference to an Integer
object which has not been initiliazed. Uninitialized references get the default value of null
and when you try to apply the intValue
() method on a null reference you get the NullPointerException
.
为了完全避免这个问题,你需要让你的引用变量引用 Integer
对象:
To avoid this problem altogether you need to make your reference variable refer to an Integer
object as:
class Test {
// now iVar1 refers to an integer object which wraps int 0.
static Integer iVar1 = new Integer(0);
// uninitialized int variable iVar2 gets the default value of 0.
static int iVar2;
public static void main(String...args) {
System.out.println(iVar1.intValue()); // prints 0.
System.out.println(iVar2); // prints 0.
}
}
这篇关于为什么在NullPointerException中使用默认值的Java Integer结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!