Java类型转换

1、类型大小

     由高到低:

                double > faoal > long > int > char , short , byte

2、强制转换

     (1)强制转换: (类型)变量名  ,是由高到低。

     (2)自动转换: 由低到高

        注意点:

               1)不能对boolean制转换

               2)不能打对象类型转换为不相干的类型

               3)把高容量转换为低要强制转换, ;例:

                       char c = 'a';
                       int d = c + 1;
                       System.out.println(d);//98
                       System.out.println((char)d);//b

               4)转换可能存在溢出,或者是精度问题, 例:    

                      //精度问题
                     System.out.println((int)23.1);//23
                     System.out.println((int)-45.89f);//-45

 

                     //操作比较大的数的时候,注意溢出问题
                     //jdk7的新特性,数字之间可以用下划线分隔
                     int money = 10_0000_0000;
                     int years = 20;
                     int total = money*years;//是负数,计算的时候溢出了
                     long total2 = money*years;//默认是int,转换之前已经存在问题
                     long total3 = money*((long)years);//先把一个转换为long
                     System.out.println(total);//-1474836480
                     System.out.println(total2);//-1474836480
                     System.out.println(total3);//20000000000

      

              

posted @ 2022-03-03 09:45  小王同学学编程  阅读(258)  评论(0)    收藏  举报
levels of contents