java - 自动装箱/拆箱 java Long 类型作为返回值时出现意外的 NullPointerException

标签 java nullpointerexception autoboxing scjp

有人可以解释一下为什么 getY() 方法会导致 NullPointerException。

public class NullTest {
    private String s = "";

    public Long getValue() {
        return null;
    }

    public Long getX() {
        return s != null ? getValue() : new Long(0);
    }

    public Long getY() {
        return s != null ? getValue() : 0L;
    }

    public static void main(String[] args) {
        NullTest nt = new NullTest();
        System.out.println("x = " + nt.getX());
        System.out.println("y = " + nt.getY());
    }
}

示例输出:

x = null
Exception in thread "main" java.lang.NullPointerException
    at NullTest.getY(NullTest.java:13)
    at NullTest.main(NullTest.java:19)

最佳答案

表达式 s != null ? 的类型getValue() :0Llong,而不是 Long。因此,如果 s != null 为 true 并且 getValue()null,则在尝试时会抛出 NullPointerExcetpionnull 取消装箱为 long

您在 getX() 中不会遇到此问题,因为在表达式 s != null 中? getValue() : new Long(0)getValue()new Long(0) 都是 Long,所以表达式的类型为Long,并且不进行拆箱。

关于java - 自动装箱/拆箱 java Long 类型作为返回值时出现意外的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100449/

相关文章:

Java 反射 : Code runs fine in Debugger but not in "normal" running mode

java - 自动装箱对原始包装器 ArrayList 的性能影响

Java 三元运算符 NPE 自动装箱字符串

java - Java 中的字符串连接和自动装箱

java - 使用 JOptionPane 和 JFrame 的程序中的对话框未显示我的代码中的内容

java - 使用 double 仅显示小数点后两位数

java - 什么是NullPointerException,我该如何解决?

java - 当其他应用程序使用麦克风时,如何获取麦克风数据?

java - 相对于背景图像的跨平台布局

android - 如何从自定义 ListView 数组适配器类中的 ListView 中删除行并刷新 ListView 中的剩余项目?