java - 带有条件运算符(三元运算符)但不是 if else 的空指针异常

标签 java nullpointerexception

<分区>

如果我使用三元运算符,我会得到空指针异常。

Integer val = null;
Object res = val == null ? val : val.intValue();

但不是 if else

    Integer val = null;
    Object res;
  if( val == null ) {
      res  = val;
  } else {
      res = val.intValue();
  }

谁能解释一下为什么?

谢谢 苏达尔

最佳答案

您遇到的行为源于确定三元条件表达式类型的规则。

在你的例子中,表达式的类型

val == null ? val : val.intValue();

int

这由 JLS 15.25. 指定:

The type of a conditional expression is determined as follows:

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.

  • If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

第二个操作数是Integer,第三个操作数是int,因此表达式的类型是int

因此,当 val == null 时,val 被拆箱(即 val.intValue() 被调用以获得 null 值)和 NullPointerException 被抛出。

在你的 if-else 表达式中 val 当它的值为 null 时不会被拆箱(因为你将它分配给一个 Object 变量,所以没有 空指针异常

也就是说,由于您将一个 Integer 变量分配给一个 Object 变量,所以您在任何一个片段中的条件都是毫无意义的(因为将一个 int 分配给一个 Object 变量简单地将 int 装回 Integer)。

你可以简单地赋值

Object res = val;

并毫无异常(exception)地得到相同的最终结果。

关于java - 带有条件运算符(三元运算符)但不是 if else 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331912/

相关文章:

java - 是否需要在 Swing 的 UI Thread 上更新 UI?

java - System.out.println() 不会抛出异常,但 System.in.read() 会抛出异常,为什么?

Java:高效插入LinkedList

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

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

java - 如何清空(或重置)一个编辑文本

java - 在 Java 中,为什么数组不能是类型变量的边界,但可以是通配符的边界?

java - 为什么在检查数组字符串是否为空时会出现空指针异常?

java - 尝试在 Eclipse 中使用资源时出现 NullPointerException

android - 尝试使用 FileProvider (Android) 获取 URI 时出现 NullPointerException