类型转换

110 阅读1分钟

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

容量 | ---|--- 低 -----------------------------------------------------> 高 | byte -> short -> char -> int -> long -> float -> double | ==运算中,不同类型的数据先转换为同一类型,然后进行运算==

2. 强制类型转换

由高容度类型转为低容量类型 高 ------> 低
方式:(类型)变量名

3. 自动类型转换

由低容量类型转为高容量类型 低 ------> 高 方式:自动转换

注意点

  1. 不能对布尔值进行转换
  2. 不能把对象类型转换为不相干的类型
  3. 在把高容量转换为低容量的时候,强制转换
  4. 转换的时候可能存在内存溢出,或者精度问题
public class Dame02 {
    public static void main(String[] args) {
        //强制类型转换  高 -> 低
        int i = 128;
        //内存溢出
        byte b = (byte) i;
        System.out.println(i);//128
        System.out.println(b);//-128

        //自动类型转换
        int i1 = 128;
        double d = i;
        System.out.println(i);//128
        System.out.println(d);//128.0

        //精度问题
        System.out.println((int)28.75);//28
        System.out.println((int)43.75f);//43

        char a = 'a';
        int i2 = a + 1;
        System.out.println(i2);//98
        System.out.println((char)i2);//b

    }
}


  1. 操作比较大的数的时候,注意内存溢出问题
public class Dame03 {
    public static void main(String[] args) {
        //操作比较大的数的时候,注意内存溢出问题
        //JDK7新特性,数字之间可以用下划线分隔
        int money = 10_0000_0000;
        System.out.println(money);
        int years = 20;
        int total1 = money * years;
        System.out.println(total1);//-1474836480
        long total2 = money * years;
        System.out.println(total2);//-1474836480
        long total3 = money * ((long)years);
        System.out.println(total3);//20000000000
    }
}