006 数据类型转换

类型转换

因为是强类型语言,所以有时候进行运算的时候需要用到类型转换

运算中不同类型数据要先转化为同一类型,然后再进行运算

byte short char int long float double

小数的优先级高于整数

强制类型转换:高到低,大取值范围到小取值范围

public class DataType {
    public static void main(String[] args) {
        int i = 123;
        byte b = (byte)i;
        System.out.println(b);//正常输出123
        int i1 = 128;
        byte b1 = (byte)i1;
        Byte
        System.out.println(b1);//输出-128,因为超过byte的取值范围,出现了溢出,可以输入Byte然后按住ctrl点击查看取值范围,单数输出多少不一定
    }
}
  1. 不能对布尔值进行转换
  2. 不能把不相干的类型进行转换
  3. 高容量转低容量的时候要强制转换
  4. 转换可能存在溢出,精度问题
        System.out.println((int)25.6);// turn to 25
        System.out.println((int)-99.5);//turn to -99

例子:

        char c = 'A';
        int e = c +1;
        System.out.println(e);
        System.out.println((char)e);// result B

操作大数的时候注意溢出问题

public class demo5 {
    public static void main(String[] args) {
        int money = 10_0000_0000;
        int year = 20;
        int total;
        System.out.println(total=money*year);// result -1474836480 数字太大导致溢出
    }
}

几种处理方式

public class demo5 {
    public static void main(String[] args) {
        int money = 10_0000_0000;
        int year = 20;
        int total;
        long total1;
        System.out.println(total=money*year);// result -1474836480 数字太大导致溢出
        System.out.println(total1=money*year);//还是溢出,因为只改变了装结果的容器的大小,结果在生成时已经溢出了,需要在前面就转换为大容量的
        System.out.println("===========================");
        long money1 = 10_0000_0000;
        System.out.println(total1=money1*year);//total1和money1已经改为大容量的类型了,所以不会再溢出
        System.out.println("===========================");
        long year1=20;
        System.out.println(total1=money*year1);//只是把year1和total1变为long类型也可以
        System.out.println("===========================");
        System.out.println(total1=year*(long)money);//直接在运算的时候把类型转换为long
    }

long类型最好用大写的,不要和数字1混淆

posted @ 2021-02-18 17:33  ytytytyt  阅读(54)  评论(0)    收藏  举报