类型转换陷阱:Java中不同类型的相互转换风险演示

原创 柔光的暖阳◎ 2024-12-11 20:00 103阅读 0赞

在Java编程中,类型转换是一种常见的操作。然而,如果处理不当,就可能会引发类型转换陷阱,导致程序错误甚至崩溃。

以下是一个简单的示例,展示了不同类型转换的风险:

  1. public class TypeConversionExample {
  2. int num = 10; // integer
  3. double d = 3.14; // double
  4. // 正确的类型转换:将double转换为int
  5. int convertedNum = (int) d;
  6. System.out.println("Converted Integer: " + convertedNum); // 3
  7. // 错误的类型转换:尝试将int转换为double
  8. double convertedDouble = (double) num; // 这会抛出ArithmeticException:conversion is impossible because the source type has no compatible conversion to the target type
  9. System.out.println("Converted Double: " + convertedDouble); // 这行代码不会执行,因为会抛出异常
  10. }

在上述示例中,我们首先正确地将double类型的值转换为int类型。然后尝试错误地将int类型的值转换为double类型。

最后,你会发现double convertedDouble = (double) num;这行代码会抛出ArithmeticException: conversion is impossible because the source type has no compatible conversion to the target type异常,因为我们试图将整数类型(int)转换为双精度浮点类型(double),但Java不支持这种直接的类型转换。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读