5、类型转换

类型转换

1、由于Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换

image-20210618141934846

2、运算中,不同类型的数据先转换为同一类型,然后进行运算

3、强制类型转换

        int i = 128;
        byte b = (byte) i;  //内存溢出

        //强制转换  (类型)变量  高--低
        System.out.println(i);
        System.out.println(b);

image-20210618144549548

4、自动类型转换

        //自动转换  低--高
        int i1 = 123546;
        double d = i1;
        float f = i1;
        System.out.println(i1);
        System.out.println(d);
        System.out.println(f);

		char c = 'a';
        int i2 = c + 1;
        System.out.println(i2);
        System.out.println((char)(i2));

image-20210618144649962

5、注意

  • 不能对布尔值进行转换
  • 不能把对象类型转换为不相干的类型
  • 把高容量转换到低容量的时候,强制转换
  • 转换的时候可能存在内存溢出,或者精度问题

6、扩展

        //操作比较大的数时,注意溢出问题
        //JDK7新特性,数字之间可以用下划线分割
        int money = 10_0000_0000;
        int year = 20;
        int total = money * year;
        System.out.println(total);  //-1474836480,计算的时候溢出了
        long total2 = money * year;
        System.out.println(total2); //默认是int,转换之前就已经出现问题了

        long total3 = (long) money * year;
        System.out.println(total3);

image-20210618144836049

posted @ 2021-06-23 23:12  多瑞C  阅读(80)  评论(0)    收藏  举报