类型的转换

发布时间 2023-10-01 20:30:42作者: 7Z/

类型转换

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

低《------------------------------------------------------------------》高

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

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

public class Demo01 {
    public static void main(String[] args) {
        //强制转换 (类型)变量名 高到低
        int i = 128;
        byte b = (byte) i; //内存溢出

        //自动转换  低到高
        int i2 = 128;
        double b2 = i2;
        System.out.println(i);
        System.out.println(b);
        /*注意点
        * 1.不能对布尔进行转换
        * 2.不能把对象类型转换为不相干的类型
        * 3.在高容量转到低容量的时候,需要强制转换;反之自动转换
        * 4.转换的时候可能存在内存溢出,或者精度问题*/
        char c = 'a';
        int c2 = c+1;
        System.out.println(c2);
        System.out.println((char) c2);
        System.out.println("=============================================");
        //操作比较大的时候 注意溢出问题
        //Jdk7 新特性 数字之间可以用下划线分割 而不会被输出;
        int money = 10__000__00000;
        int years = 20;
        int total = money * years; 
        System.out.println(total);//-1474836480 计算的时候内存溢出
        long total2 =(long) money *  years; //先把一个数转换为long类型
        System.out.println(total2);
    }

}