Java自动装箱与拆箱

Java自动装箱与拆箱

jdk5新特性, 自动装箱 和 拆箱

装箱 和 拆箱, 说的就是一个问题

基本数据类型 和 包装类 的相互转换

1. 自动装箱 (基本数据类型 -> 包装类)

package com.beyondx.java;
import org.junit.test;

public class WrapperTest {
    @Test
    public void test3() {
        int num1 = 10;
        
        // 基本数据类型 -> 包装类, 自动装箱
        // 自动装箱, 一个int型变量, 直接赋给了一个类
        /**
        * 自动装箱
        * 形如 int num2 = 10;
        *     Integer in1 = num2;
        
        * boolean b1 = true;
        * Boolean b2 = b1;
        */
        method(num1);
    }
    
    public void method(Object obj) {
        System.out.println(obj);
    }
    
    
    @Test
    public void test2() {
        Integer in1 = new Integer(12);
        
        int i1 = in1.intValue();
        System.out.println(i1 + 1);
        
        Float f1 = new Float(12.3);
        float f2 = f1.floatValue();
        System.out.println(f2 + 1);
    }
}

2. 自动拆箱 (包装类 -> 基本数据类型)

package com.beyondx.java;
import org.junit.org;

public class WrapperTest{
    @Test
    public void test4() {
        int num2 = 10;
        
        // 自动装箱
        Integer in1 = num2;
        
        boolean b1 = true;
        Boolean b2 = b1;
        
        // 手动拆箱: 包装类 -> 基本数据类型
        System.out.println(in1.toString());
        
        // 自动拆箱
        int num3 = in1;
        System.out.println(num3);
        
    }
}

参考链接

https://www.bilibili.com/video/BV1Kb411W75N?p=307

posted on 2021-11-03 20:16  beyondx  阅读(42)  评论(0编辑  收藏  举报

导航