八种基本数据类型的大小,以及他们的封装类-Java

135 阅读1分钟

在 Java 中,有八种基本数据类型(primitive types),每种基本数据类型都有对应的封装类(wrapper classes)。以下是这些基本数据类型的大小及其对应的封装类:

基本数据类型及其大小

  1. byte

    • 大小:8 位(1 字节)
    • 封装类:Byte
  2. short

    • 大小:16 位(2 字节)
    • 封装类:Short
  3. int

    • 大小:32 位(4 字节)
    • 封装类:Integer
  4. long

    • 大小:64 位(8 字节)
    • 封装类:Long
  5. float

    • 大小:32 位(4 字节)
    • 封装类:Float
  6. double

    • 大小:64 位(8 字节)
    • 封装类:Double
  7. char

    • 大小:16 位(2 字节)
    • 封装类:Character
  8. boolean

    • 大小:1 位(实际存储时通常占用 1 字节)
    • 封装类:Boolean

示例代码

以下是一个简单的示例,展示了如何使用这些基本数据类型及其封装类:

public class PrimitiveTypesExample {
    public static void main(String[] args) {
        // 基本数据类型
        byte byteValue = 10;
        short shortValue = 100;
        int intValue = 1000;
        long longValue = 100000L;
        float floatValue = 3.14f;
        double doubleValue = 3.141592653589793;
        char charValue = 'A';
        boolean booleanValue = true;

        // 封装类
        Byte byteObject = new Byte(byteValue);
        Short shortObject = new Short(shortValue);
        Integer intObject = new Integer(intValue);
        Long longObject = new Long(longValue);
        Float floatObject = new Float(floatValue);
        Double doubleObject = new Double(doubleValue);
        Character charObject = new Character(charValue);
        Boolean booleanObject = new Boolean(booleanValue);

        // 输出
        System.out.println("byte: " + byteValue + ", Byte: " + byteObject);
        System.out.println("short: " + shortValue + ", Short: " + shortObject);
        System.out.println("int: " + intValue + ", Integer: " + intObject);
        System.out.println("long: " + longValue + ", Long: " + longObject);
        System.out.println("float: " + floatValue + ", Float: " + floatObject);
        System.out.println("double: " + doubleValue + ", Double: " + doubleObject);
        System.out.println("char: " + charValue + ", Character: " + charObject);
        System.out.println("boolean: " + booleanValue + ", Boolean: " + booleanObject);
    }
}

在这个示例中,我们创建了各种基本数据类型的变量,并使用它们的封装类创建了相应的对象。然后,我们输出这些变量和对象的值。