Integer 为空赋值给int

Java中Integer与int类型转换异常处理

今天遇到了一个异常,将Integer的值赋值给int时不会自动将Integer 的null转化为0,而是报运行时异常,空指针

 public static void main(String[] args) throws Exception { 
          Integer i = null;
          test(i);
          System.out.print(i);
      } 

      public static void test(int i){
          System.out.print(i);
          int n = 0;
          n = i;
          System.out.print(n);
      }





public static void main(String[] arg){
        int i = 0;
        test(i);

        Map<Long,Integer> map = new HashMap<Long,Integer>();
        map.put((long) 1, null);

        test2(map.get(1));
    }
    public static void test(Integer id){
        System.out.print("+++++++++++++++++" +   id);
    }

    public static void test2(Integer id){
        int i = id;
        System.out.print(id);
    }
在 Java 中,自动装箱(Autoboxing)是指将基本数据类型(如 `int`、`double` 等)自动转换为其对应的包装类(如 `Integer`、`Double` 等)的过程。这一特性是在 Java 5 中引入的,属于语言层面上的重要改进之一[^1]。 根据题干中的选项分析: - **A) Assigning an `int` type to an `Integer` type variable** 此情况会触发自动装箱。Java 编译器会自动将 `int` 类型的值转换为 `Integer` 类型对象。例如: ```java Integer obj = 10; // 自动装箱 ``` 此操作在底层等价于调用 `Integer.valueOf(10)`,属于自动装箱机制的一部分 [^1]。 - **B) Assigning an `Integer` type variable to an `int` type variable** 此情况会触发自动拆箱(Unboxing),即将 `Integer` 对象自动转换为 `int` 类型。例如: ```java Integer obj = 10; int value = obj; // 自动拆箱 ``` 该行为属于与自动装箱相对的过程,并非装箱操作。 - **C) Calling the `Integer.parseInt()` method** 此方法用于将字符串解析为基本类型 `int`,与自动装箱无关。例如: ```java int value = Integer.parseInt("123"); ``` 该过程不涉及基本类型与包装类之间的自动转换。 - **D) Calling the `Integer.valueOf()` method** 调用 `Integer.valueOf()` 是显式地将基本类型转换为包装类对象的行为,虽然其功能与自动装箱相同,但它是显式调用而非自动触发。例如: ```java Integer obj = Integer.valueOf(10); ``` 此行为属于手动装箱,不属于自动装箱的范畴。 ### 正确答案 因此,**选项 A 是唯一会触发自动装箱的情况**。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值