为什么使用默认值的 Java Integer 会导致 NullPointerException? [英] Why does using a default-valued Java Integer result in a NullPointerException?

查看:23
本文介绍了为什么使用默认值的 Java Integer 会导致 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 是对尚未初始化的 Integer 对象的引用.未初始化的引用获得 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.
 }
}

这篇关于为什么使用默认值的 Java Integer 会导致 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆