Java基础语法3-数据类型转换

数据类型的转换

从低到高-------->

byte,short,char -> int -> long -> float -> double

  • Java是强类型语言,在进行运算时需要进行类型转换
  • 运算中,不同类型的数据先转化为同一类型,然后进行运算
  • 强制类型转换
  • 自动类型转换

数据转换时注意点

  1. 不能对布尔型进行转换
  2. 不能把对象类型转换为不想干的类型
  3. 在高容量转换为低容量的时候,使用强制转换
  4. 转换时可能存在精度问题或内存溢出!***
public class Demo7 {
    public static void main(String[] args) {
        // byte,short,char -> int -> long -> float -> double

        // 高->低, 需要强制转换
        int a =  130;  // 0b10000010
        byte b = (byte) a;  // 10000010取反:11111101加1得到:11111110,-126
        System.out.println(b);  // 结果:-126

        // 低->高,自动转换
        double c = 12.45 + a;
        System.out.println(c);  // 结果:142.45

        // 高->低, 需要强制转换,产生的精度问题
        System.out.println((int) 23.9);  // 结果:23
        System.out.println((int) -12.785f);  // 结果:-12

        char ch = 'a';
        int d = ch + 1;  //自动转换
        System.out.println(d);  // 结果:98
        System.out.println((char) d);  // 结果:b

        // 操作比较大的数字时,需要注意数字溢出问题
        int money = 10_0000_0000;  // JDK新特性,数字间可以用_分割
        int years = 20;
        int total = money * years;
        System.out.println(total); // 结果:-1474836480

        long total2 = money * years;
        System.out.println(total2); // 结果:-1474836480

        long total3 = money*((long)years);
        System.out.println(total3);  // 结果:20000000000

    }
}
posted @ 2022-05-06 14:38  浅浅水声  阅读(30)  评论(0编辑  收藏  举报