1. 程式人生 > 其它 >Java基礎語法3-資料型別轉換

Java基礎語法3-資料型別轉換

資料型別的轉換

從低到高-------->

byte,short,char -> int -> long -> float -> double

  • Java是強型別語言,在進行運算時需要進行型別轉換
  • 運算中,不同型別的資料先轉化為同一型別,然後進行運算
  • 強制型別轉換
  • 自動型別轉換

資料轉換時注意點

  1. 不能對布林型進行轉換
  2. 不能把物件型別轉換為不想幹的型別
  3. 在高容量轉換為低容量的時候,使用強制轉換
  4. 轉換時可能存在精度問題或記憶體溢位!***
public class Demo7 {
    public static void main(String[] args) {
        // byte,short,char -> int -> long -> float -> double

        // 高->低, 需要強制轉換
        int a =  130;  // 0b10000010
        byte b = (byte) a;  // 10000010取反:11111101加1得到:11111110,-126
        System.out.println(b);  // 結果:-126

        // 低->高,自動轉換
        double c = 12.45 + a;
        System.out.println(c);  // 結果:142.45

        // 高->低, 需要強制轉換,產生的精度問題
        System.out.println((int) 23.9);  // 結果:23
        System.out.println((int) -12.785f);  // 結果:-12

        char ch = 'a';
        int d = ch + 1;  //自動轉換
        System.out.println(d);  // 結果:98
        System.out.println((char) d);  // 結果:b

        // 操作比較大的數字時,需要注意數字溢位問題
        int money = 10_0000_0000;  // JDK新特性,數字間可以用_分割
        int years = 20;
        int total = money * years;
        System.out.println(total); // 結果:-1474836480

        long total2 = money * years;
        System.out.println(total2); // 結果:-1474836480

        long total3 = money*((long)years);
        System.out.println(total3);  // 結果:20000000000

    }
}