Java 类型强制转换

39 阅读2分钟

📚 类型转换概述

1. Java数据类型层次

                  数值类型
                      |
        ---------------------------------
        |                               |
    整型类型                        浮点类型
        |                               |
    -----------                    -----------
    |         |                    |         |
   byte      short               float     double
    |         |
   char      int
              |
             long

2. 两种类型转换

// 1. 自动类型转换(隐式转换)
// 2. 强制类型转换(显式转换)

🔄 自动类型转换(隐式转换)

1. 转换规则(从小到大)

byteshortintlongfloatdoublechar

2. 自动转换示例

public class AutoConversion {
    public static void main(String[] args) {
        // 1. byte → short → int → long
        byte b = 10;
        short s = b;      // byte自动转short
        int i = s;        // short自动转int
        long l = i;       // int自动转long
        System.out.println("b=" + b + ", s=" + s + ", i=" + i + ", l=" + l);
        
        // 2. int → float → double
        int intValue = 100;
        float f = intValue;    // int自动转float
        double d = f;          // float自动转double
        System.out.println("intValue=" + intValue + ", f=" + f + ", d=" + d);
        
        // 3. char → int
        char c = 'A';
        int charToInt = c;     // char自动转int(ASCII码)
        System.out.println("c=" + c + ", charToInt=" + charToInt); // 输出65
        
        // 4. 表达式中的自动提升
        byte b1 = 10;
        byte b2 = 20;
        // byte result = b1 + b2;  // ❌ 编译错误!
        int result = b1 + b2;     // ✅ byte运算自动提升为int
        System.out.println("result=" + result);
        
        // 5. 混合运算的提升规则
        int x = 10;
        long y = 20L;
        float z = 30.5f;
        double w = 40.5;
        
        // 运算结果自动提升为最大的类型
        double total = x + y + z + w;  // 最终为double
        System.out.println("total=" + total);
    }
}

🚨 强制类型转换(显式转换)

1. 基本语法

目标类型 变量名 = (目标类型) 源变量或表达式;

2. 整型之间的强制转换

public class IntegerCast {
    public static void main(String[] args) {
        // 1. 大类型转小类型(可能丢失数据)
        int intValue = 300;
        byte byteValue = (byte) intValue;  // 强制转换
        System.out.println("intValue=" + intValue + ", byteValue=" + byteValue);
        // 输出:intValue=300, byteValue=44(溢出)
        
        // 2. long转int
        long longValue = 1234567890123L;
        int intFromLong = (int) longValue;  // 高位被截断
        System.out.println("longValue=" + longValue + ", intFromLong=" + intFromLong);
        
        // 3. 负数的转换
        int negativeInt = -100;
        byte negativeByte = (byte) negativeInt;
        System.out.println("negativeInt=" + negativeInt + 
                         ", negativeByte=" + negativeByte);
        
        // 4. 合理范围内的转换
        int safeInt = 100;
        byte safeByte = (byte) safeInt;  // 安全,不会丢失数据
        System.out.println("safeByte=" + safeByte);  // 输出100
    }
}

3. 浮点型与整型的强制转换

public class FloatIntegerCast {
    public static void main(String[] args) {
        // 1. double/float → int(小数部分被截断)
        double d = 123.456;
        int i = (int) d;  // 只保留整数部分
        System.out.println("d=" + d + ", i=" + i);  // 输出123
        
        // 2. float → int
        float f = 78.9f;
        int i2 = (int) f;
        System.out.println("f=" + f + ", i2=" + i2);  // 输出78
        
        // 3. 四舍五入的技巧
        double price = 99.99;
        int rounded = (int) Math.round(price);  // 使用Math.round四舍五入
        System.out.println("price=" + price + ", rounded=" + rounded);  // 输出100
        
        // 4. 手动四舍五入
        double value = 56.78;
        int rounded2 = (int) (value + 0.5);
        System.out.println("value=" + value + ", rounded2=" + rounded2);
        
        // 5. int → float/double(安全,但可能损失精度)
        int bigInt = 123456789;
        float floatFromInt = (float) bigInt;
        System.out.println("bigInt=" + bigInt + 
                         ", floatFromInt=" + floatFromInt);
    }
}

4. 精度丢失问题

public class PrecisionLoss {
    public static void main(String[] args) {
        // 1. 浮点数小数部分丢失
        double precise = 3.1415926535;
        float lessPrecise = (float) precise;  // 精度降低
        System.out.println("double: " + precise);
        System.out.println("float:  " + lessPrecise);
        
        // 2. 大整数转浮点数
        int largeNumber = 123456789;
        float floatNumber = largeNumber;  // 自动转换
        // float只有6-7位有效数字,可能不精确
        System.out.println("int: " + largeNumber);
        System.out.println("float: " + floatNumber);
        
        // 3. 浮点数运算精度问题
        double d1 = 0.1;
        double d2 = 0.2;
        System.out.println("0.1 + 0.2 = " + (d1 + d2));  // 输出0.30000000000000004
    }
}