類型轉換及注意事項


類型轉換

  1. 由於Java是強類型語言,要進行有些運算時需要用要類型轉換

    由低到高為:

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

  2. 運算中,不同類型的數據先轉化為同一類型,然后進行運算

  3. 強制類型轉換

  4. 自動類型轉換

類型轉換注意點

  1. 不能對布爾型進行轉換

  2. 不能把對象類型轉換成不相干的類型

  3. 在把高容量轉換到低容量的時候,強制轉換

  4. 轉換的時候可能會存在內存溢出或者精度的問題

實例1:

 public class Demo05 {
     public static void main(String[] args) {
         int i = 128;
         //Byte
         byte b = (byte)i ;// 內存溢出
 
         int j = 128;
         //Byte
         double d = j ;
         //強制類型轉換 (類型)變量名 高--低
         //自動轉換 低--高
 
         System.out.println(i);
         System.out.println(b);
         System.out.println(j);
         System.out.println(d);
 
         /*
         注意點:
         1、不能對布爾型進行轉換
         2、不能把對象類型轉換成不相干的類型
         3、在把高容量轉換到低容量的時候,強制轉換
         4、轉換的時候可能會存在內存溢出或者精度的問題
          */
         System.out.println("============================================");
         System.out.println((int)23.7); //23
         System.out.println((int)-45.89f); //-45
 
         System.out.println("============================================");
         char c = 'a';
         int e = c + 1;
         System.out.println(e);
         System.out.println((char)e);
 
 
    }
 }

實例2:

 public class Demo06 {
     public static void main(String[] args) {
         //操作比較大的數的時候,注意溢出問題
         //JDK7 新特性 數字之間可以用下划線分割
         int money = 10_0000_0000;
         int year = 20;
         int total = money * year;// -1474836480 計算時溢出了
         long total2 = money * year; //默認是int,轉換之前已經溢出了
 
         long total3 = money * ((long)year); //先把一個數轉換成long
 
         System.out.println(total);
         System.out.println(total2);
         System.out.println(total3);
 
         // L l
    }
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM