类型转换

类型转换的依次顺序

低----------→-----------→----------→----------高

byte,char,short < int < long < float < double

 

(浮点数优先级大于整数) 

运算中不同类型的数据要转化成同一类型,然后计算。

        int i =128;
        byte p= (byte) i;       //内存溢出
        System.out.println(i);    //128
        System.out.println(p);    //-128
        //转换过程中避免内存溢出
        

强制转换 (类型)变量名 高→低

自动转换  低→高

注意浮点数(float,double)与整数转换存在精度问题

        int i =128;
        byte p= (byte) i;       //溢出
        System.out.println(i);    //128
        System.out.println(p);    //-128
        //转换过程中避免内存溢出
        System.out.println("-----------------------------------");
        int monney = 10_0000_0000;
        int years = 20;
        int total = monney*years;   //-1474836480 溢出
        long total1 = monney*years; //-1474836480,默认int 转换之前
        long total2=monney*((long)years);  //转换一个数就不存在问题
        System.out.println(total2);

    }
}
原文地址:https://www.cnblogs.com/li369/p/14017247.html