3.类型转换

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

    低----------------------------------------------->高
    byte, short, char -> int -> long -> float -> double 
    
  • 运算中,不同类型的数据先转换位同一类型,然后进行运算。

  • 强制类型转换——由高到低,强制转换

  • 自动类型转换——由低到高,自动转换

注意点:

  1. 不能对布尔值进行转换。

  2. 不能把对象类型转换为不相干的类型。

  3. 转换的时候可能存在内存溢出、或者精度问题。

  4. 操作比较大的数的时候,注意溢出问题。

  5. 在进行计算时,如果计算结果超出该类型范围,要在计算前进行类型转换,因为当计算完成时会自动对结果进行类型转换,此时在转换为其他类型没有意义,结果已经出错。

    如:

    public class Test01 {
    
        public static void main(String[] args) {
    
            int money = 10_0000_0000;//JDK7新特性,数字之间用下划线分割
            int years = 20;
    
            int total = money * years;
            long total1 = money * years;
            long total2 = money * (long)years;
            long total3 = (long)money * years;
    
            System.out.println(total);
            System.out.println(total1);
            System.out.println(total2);
            System.out.println(total3);
        }
    }
    

    运行结果如图:

Java基础语法3_强制转换