JAVA数据类型转换

JAVA数据类型转换

不同的数据类型之间要进行运算就需要进行数据类型转换,转换分为强制类型转换和自动(隐式)类型转换。

Java的基本数据类型包括八种:

整数类型(byte,short,int long)

浮点数类型(double,float)

布尔类型(boolean)

字符类型(char)

类型从小到大依次为

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

强制类型转换

数据类型由大到小转换时,需要用到强制类型转换

例如:

       int i = 128;
       byte b = (byte)i;  //byte最大值为127,内存溢出,需要强制类型转换
                         

注意:在进行强制类型转换时会出现数据精度的丢失。例如:double类型变量a的值为5.123,强制转换成int类型后数值为5,小数位舍弃,产生了精度丢失。

自动类型转换

数据类型由小到大转换时,系统自动会进行自动类型转换

例如:

      int i1 = 12;
      double b1 = i1;

      System.out.println(b1); //12.0

拓展

溢出问题

public class NewDemo01 {
    public static void main(String[] args) {
        
        //操作比较大的数的时候,注意溢出问题
        int salary = 10_0000_0000;//JDK7新特性,数字之间可以用_分割
        int years = 20;

        int total = salary*years;   //计算后结果溢出,超过了int的范围
        long total2 = salary*years; //在进行转换之前就已经溢出了

        long total3 = salary*((long)years); //先将其中一个值转换成long类型,就可以得到正确值

        System.out.println(total);//-1474836480
        System.out.println(total2);//-1474836480
        System.out.println(total3);//20000000000
    }
}
posted @ 2020-11-10 20:24  IAimHigher  阅读(86)  评论(0)    收藏  举报