java数据类型转换

类型转换

1. 强制转换
格式:(类型)变量名 高—>低
例如:int i = 128;byte = (int)i;
2. 自动转换
格式: 低—>高

//注意点:
//1.不能对布尔型强转
//2. 不能转换为无关变量类型
//3. 高容量转换到低容量时,使用强转
//4. 转换时可能出现内存溢出、精度丢失问题!

代码展示:

public class 类型转换 {

    public static void main(String[] args) {
        int i = 128;
        byte b = (byte)i;
        double c = i;
        System.out.println(i);
        System.out.println(b);
        System.out.println(c);
        System.out.println("----------------------------");

        int money  = 10_0000_0000;
        int year = 20;
        System.out.println(money*year);//内存溢出
        //解决方法:
        long result = (long) money*year;
        System.out.println(result);
    }
}
原文地址:https://www.cnblogs.com/shimmernight/p/13441743.html