Day8(类型转换,强制转换,自动转换)

类型转换

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

  • 低——————》高

  • byte,short,char–>int–>long–>float–>double

  • 运算中,不同类型的数据线转化为同一类型,然后进行运算

  • 强制类型转换

        int a1 = 109;
        byte b1 = (byte)a1;//强制转换 高转低需要强制转换,(类型)变量名
        int a2 = 199;
        byte b2 = (byte)a2;//内存溢出
        double a3 = 4321.111;
        long b3 = (long)a3;
        System.out.println(b1);
        System.out.println(b2);
        System.out.println(b3);
109
-57
4321
  • 自动类型转换
        int c1 = 999;
        long d1 = c1;//自动转换
        int c2 = 999;
        long d2 = (long)c2;//低容量转高容量会自动转换,不需要强制转换加(long)
999
999
  • 注意点
    1. 不能对布尔值进行转换
    2. 不能把对象类型转换为不相干的类型
    3. 把高容量转换到低容量的时候,要强制转换
    4. 转换的时候可能存在内存溢出,或者精度问题
        System.out.println((int)12.5);//精度问题
        System.out.println((byte)222);//内存溢出
        System.out.println((long)3333.2);//精度问题
12
-34
3333
char c3 = '瓜';
        int d3 = c3+1;
        char c4 = '柯';
        int d4 = c4+1;
        System.out.println(d3);
        System.out.println(d4);
        System.out.println((char)d3);
        System.out.println((char)d4);
29917
26608
瓝
柰
  • 操作比较大的数的时候,注意溢出问题
        int money = 10_0000_0000;//jdk7之后数字之间可以用下划线分割
        int year = 20;
        System.out.println(money*year);//计算的时候溢出了
        int total = money*year;
        System.out.println(total);//计算的时候溢出了
        long total2 = money*year;
        System.out.println(total2);//默认是int,转换之前就出现问题了
        long total3 = money*((long)year);
        long total4 = ((long)money)*year;//先把一个数转化为long
        System.out.println(total3);
        System.out.println(total4);
-1474836480
-1474836480
-1474836480
20000000000
20000000000

猜你喜欢

转载自blog.csdn.net/SuperrWatermelon/article/details/112458387
今日推荐