第11章

Java类型转换

掌握自动转换与强制转换的原理与应用

学习目标

Java类型转换概述

类型转换是Java编程中的重要概念,它允许我们在不同数据类型之间进行转换。理解类型转换的机制对于编写正确和高效的Java程序至关重要。

类型转换的分类:
• 自动类型转换(隐式转换):由编译器自动完成
• 强制类型转换(显式转换):需要程序员明确指定
• 包装类转换:基本类型与包装类之间的转换
• 字符串转换:字符串与其他类型之间的转换

类型转换层次图

byte
short
int
long
float
double

箭头方向表示自动类型转换的方向(从小到大)

类型转换详解

自动类型转换

示例:
// 自动类型转换(向上转换)
byte b = 10;
short s = b;    // byte → short
int i = s;      // short → int
long l = i;     // int → long
float f = l;    // long → float
double d = f;   // float → double

// 表达式中的自动提升
int x = 5;
float y = 3.2f;
double result = x + y; // int和float提升为double
  • 从小范围到大范围的转换
  • 不会丢失精度(除了long到float)
  • 编译器自动完成
  • 表达式中的类型提升

强制类型转换

示例:
// 强制类型转换(向下转换)
double d = 3.14159;
float f = (float) d;    // double → float
long l = (long) f;      // float → long
int i = (int) l;        // long → int
short s = (short) i;    // int → short
byte b = (byte) s;      // short → byte

// 可能的精度损失
double pi = 3.14159;
int intPi = (int) pi;   // 结果:3(小数部分丢失)
  • 从大范围到小范围的转换
  • 可能丢失精度或数据
  • 需要显式指定转换类型
  • 编译器会给出警告

包装类转换

示例:
// 自动装箱(基本类型 → 包装类)
int primitive = 42;
Integer wrapper = primitive;  // 自动装箱

// 自动拆箱(包装类 → 基本类型)
Integer wrapperInt = 100;
int primitiveInt = wrapperInt; // 自动拆箱

// 包装类之间的转换
Integer intValue = 123;
Double doubleValue = intValue.doubleValue();
String stringValue = intValue.toString();
  • 自动装箱和拆箱
  • 包装类提供转换方法
  • null值需要特别注意
  • 性能开销相对较大

字符串转换

示例:
// 其他类型转换为字符串
int num = 123;
String str1 = String.valueOf(num);    // "123"
String str2 = Integer.toString(num);  // "123"
String str3 = num + "";              // "123"

// 字符串转换为其他类型
String numStr = "456";
int intValue = Integer.parseInt(numStr);
double doubleValue = Double.parseDouble("3.14");
boolean boolValue = Boolean.parseBoolean("true");
  • String.valueOf()方法
  • 包装类的parse方法
  • 字符串连接自动转换
  • 需要处理格式异常

类型转换规则

自动类型转换条件

源类型 目标类型 转换方式 是否安全
byte short, int, long, float, double 自动转换 ✅ 安全
short int, long, float, double 自动转换 ✅ 安全
char int, long, float, double 自动转换 ✅ 安全
int long, float, double 自动转换 ⚠️ float可能精度损失
long float, double 自动转换 ⚠️ float可能精度损失
float double 自动转换 ✅ 安全
注意:虽然long可以自动转换为float,但由于float的精度限制(23位尾数),可能会丢失精度。long类型的大整数转换为float时需要特别小心。

实际应用示例

通过一个类型转换演示程序,我们来看看如何在实际项目中正确使用各种类型转换。

类型转换综合示例:
public class TypeConversionDemo {
    public static void main(String[] args) {
        // 1. 自动类型转换示例
        System.out.println("=== 自动类型转换 ===");
        byte byteValue = 10;
        short shortValue = byteValue;  // byte → short
        int intValue = shortValue;     // short → int
        long longValue = intValue;     // int → long
        float floatValue = longValue;  // long → float
        double doubleValue = floatValue; // float → double
        
        System.out.println("byte: " + byteValue);
        System.out.println("转换后的double: " + doubleValue);
        
        // 2. 强制类型转换示例
        System.out.println("\n=== 强制类型转换 ===");
        double pi = 3.14159;
        int intPi = (int) pi;          // 精度损失
        float floatPi = (float) pi;    // 轻微精度损失
        
        System.out.println("原始值: " + pi);
        System.out.println("转换为int: " + intPi);
        System.out.println("转换为float: " + floatPi);
        
        // 3. 包装类转换示例
        System.out.println("\n=== 包装类转换 ===");
        Integer wrapperInt = 100;      // 自动装箱
        int primitiveInt = wrapperInt; // 自动拆箱
        
        // 包装类方法转换
        String numberStr = wrapperInt.toString();
        Double doubleFromInt = wrapperInt.doubleValue();
        
        System.out.println("包装类转字符串: " + numberStr);
        System.out.println("包装类转double: " + doubleFromInt);
        
        // 4. 字符串转换示例
        System.out.println("\n=== 字符串转换 ===");
        String numStr = "123";
        String floatStr = "45.67";
        String boolStr = "true";
        
        try {
            int parsedInt = Integer.parseInt(numStr);
            double parsedDouble = Double.parseDouble(floatStr);
            boolean parsedBool = Boolean.parseBoolean(boolStr);
            
            System.out.println("字符串转int: " + parsedInt);
            System.out.println("字符串转double: " + parsedDouble);
            System.out.println("字符串转boolean: " + parsedBool);
        } catch (NumberFormatException e) {
            System.out.println("数字格式错误: " + e.getMessage());
        }
        
        // 5. 表达式中的类型提升
        System.out.println("\n=== 表达式类型提升 ===");
        byte b1 = 10, b2 = 20;
        // byte运算结果自动提升为int
        int result = b1 + b2;
        System.out.println("byte运算结果: " + result);
        
        // 混合类型运算
        int intVal = 10;
        float floatVal = 3.5f;
        double mixedResult = intVal * floatVal; // 提升为double
        System.out.println("混合运算结果: " + mixedResult);
    }
}
💻 查看完整代码 - 在线IDE体验

常见问题和注意事项

类型转换陷阱

精度损失:
long bigNumber = 123456789012345L;
float floatNumber = bigNumber; // 可能丢失精度
解决方案:使用double类型或检查数值范围
整数溢出:
int maxInt = Integer.MAX_VALUE;
byte smallByte = (byte) maxInt; // 数据溢出
建议:转换前检查数值范围
字符串转换异常:
String invalidNumber = "abc";
int number = Integer.parseInt(invalidNumber); // NumberFormatException
解决方案:使用try-catch处理异常

最佳实践

安全的类型转换:
• 优先使用自动类型转换
• 强制转换前检查数值范围
• 字符串转换时处理异常
• 注意包装类的null值检查
• 使用合适的数据类型避免不必要的转换

本章小结