Integer s = 1 == status ? 1 : 2 == status ? 3 : 3 == status ? 4 : null;在这个三元表达式中status=5时为什么会抛出空指针异常

这个三元表达式抛出NullPointerException的根本原因是自动拆箱机制导致的,具体分析如下:

异常触发原理

  1. 表达式结构分析
    该表达式是嵌套的三元运算符:

    Integer s = 1 == status ? 1 : 
                2 == status ? 3 : 
                3 == status ? 4 : null;
    
  2. 关键问题点

    • status不等于1/2/3时,最终返回null
    • 但Java会将三元运算符的结果类型统一为int(因为1/3/4都是int字面量)
    • 在赋值给Integer s时,需要将null自动拆箱为int,触发NPE

解决方案

  1. 显式声明类型(推荐)
    强制指定整体表达式结果为Integer类型:

    Integer s = 1 == status ? Integer.valueOf(1) : 
                2 == status ? Integer.valueOf(3) : 
                3 == status ? Integer.valueOf(4) : null;
    
  2. 简化写法
    使用Java9+的Objects.equals()更安全:

    Integer s = switch(status) {
        case 1 -> 1;
        case 2 -> 3;
        case 3 -> 4;
        default -> null;
    };
    

根本原因总结

情况 行为 结果
三元运算符含int字面量 整体表达式类型推断为int 需要拆箱
最终返回null 尝试null.intValue() 抛出NPE
所有分支返回Integer 类型推断为Integer 正常执行

建议始终保证三元运算符各分支返回相同包装类型,避免自动类型推断风险。

你可能感兴趣的:(java)