首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 類型轉換完全指南:自動擴寬、強制縮窄、截斷與取模陷阱

     編輯:Java 相關知識

Java 型別轉換分為自動類型轉換(擴寬)與強制類型轉換(縮窄)。理解數值範圍、精度損失、補碼取模規則,能避免隱性 Bug。

自動擴寬轉換

滿足兩條件:1) 型別相容(數值型別間) 2) 目標型別範圍 ≥ 來源型別範圍。

byte → short → int → long → float → double
char → int → long → float → double

無資料遺失,編譯器自動插入轉換指令。

強制縮窄轉換

語法:(targetType) value。兩種情況:

  1. 整數縮窄:高位截斷,按目標型別範圍取模(補碼)。
    例:int 257 → (byte) 1(257 % 256 = 1)。
    int -129 → (byte) 127(-129 + 256 = 127)。
  2. 浮點轉整數:截斷小數部份(向零取整),再按整數範圍取模。
    例:double 323.142 → (int) 323 → (byte) 67(323 % 256 = 67)。

完整範例輸出

public class ConversionDemo {
    public static void main(String[] args) {
        int i = 257;
        double d = 323.142;

        byte b = (byte) i;        // 1
        System.out.println("int 257 -> byte: " + b);

        i = (int) d;              // 323
        System.out.println("double 323.142 -> int: " + i);

        b = (byte) d;             // 67
        System.out.println("double 323.142 -> byte: " + b);
    }
}
// 輸出:
// int 257 -> byte: 1
// double 323.142 -> int: 323
// double 323.142 -> byte: 67

字元與布林

  • char 可與數值型別雙向轉換(Unicode 碼點),但 boolean 不可與任何型別轉換。
  • char c = (char) 65; // 'A',int code = '中'; // 20013。

避坑清單

陷阱錯誤代碼正確做法
浮點精度誤判if (0.1 + 0.2 == 0.3)用 BigDecimal 或誤差範圍比較
長整數字面值溢位long l = 2147483648; // 編譯錯long l = 2147483648L;
byte 運算自動提升 intbyte a=1, b=2; byte c = a+b; // 編譯錯byte c = (byte)(a+b);
物件包裝類拆箱空指針Integer x = null; int y = x; // NPE檢查 null 或用 Optional

最佳實踐

  1. 優先使用 long/double 避免頻繁轉換。
  2. 金融計算嚴禁 float/double,必須用 BigDecimal。
  3. 介面設計時,參數型別盡量寬(long/double),內部再縮窄並驗證範圍。
  4. 單元測試覆蓋邊界值:Byte.MIN_VALUE, Byte.MAX_VALUE, Short.MIN_VALUE...。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved