自动装箱

89页Exercise9

Write a program that demonstrates that autoboxing works for all the primitive types and their wrappers.

public class AutoboxingDemo {
    public static void main(String[] args) {
        // 1. byte ↔ Byte
        byte bytePrimitive = 127;
        Byte byteWrapper = bytePrimitive;
        System.out.println("byte autoboxing: " + byteWrapper);

        // 2. short ↔ Short
        short shortPrimitive = 32767;
        Short shortWrapper = shortPrimitive;
        System.out.println("short autoboxing: " + shortWrapper);

        // 3. int ↔ Integer
        int intPrimitive = 2147483647;
        Integer intWrapper = intPrimitive;
        System.out.println("int autoboxing: " + intWrapper);

        // 4. long ↔ Long
        long longPrimitive = 9223372036854775807L;
        Long longWrapper = longPrimitive;
        System.out.println("long autoboxing: " + longWrapper);

        // 5. float ↔ Float
        float floatPrimitive = 3.4028235e38f;
        Float floatWrapper = floatPrimitive;
        System.out.println("float autoboxing: " + floatWrapper);

        // 6. double ↔ Double
        double doublePrimitive = 1.7976931348623157e308;
        Double doubleWrapper = doublePrimitive;
        System.out.println("double autoboxing: " + doubleWrapper);

        // 7. char ↔ Character
        char charPrimitive = 'A';
        Character charWrapper = charPrimitive;
        System.out.println("char autoboxing: " + charWrapper);

        // 8. boolean ↔ Boolean
        boolean boolPrimitive = true;
        Boolean boolWrapper = boolPrimitive;
        System.out.println("boolean autoboxing: " + boolWrapper);
    }
}

该程序演示了:

自动装箱发生在基本类型直接赋值给对应包装类时
覆盖所有8种基本类型及其包装类:
byte ↔ Byte
short ↔ Short
int ↔ Integer
long ↔ Long
float ↔ Float
double ↔ Double
char ↔ Character
boolean ↔ Boolean
每个类型都使用该类型的最大值/典型值进行演示
通过打印包装类对象验证自动装箱成功
运行结果将显示所有包装类正确存储了对应的基本类型值,证明自动装箱正常工作。

posted @ 2025-04-25 08:55  尼兰  阅读(8)  评论(0)    收藏  举报