Java 型別轉換分為自動類型轉換(擴寬)與強制類型轉換(縮窄)。理解數值範圍、精度損失、補碼取模規則,能避免隱性 Bug。
滿足兩條件:1) 型別相容(數值型別間) 2) 目標型別範圍 ≥ 來源型別範圍。
byte → short → int → long → float → double
char → int → long → float → double
無資料遺失,編譯器自動插入轉換指令。
語法:(targetType) value。兩種情況:
int 257 → (byte) 1(257 % 256 = 1)。int -129 → (byte) 127(-129 + 256 = 127)。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 運算自動提升 int | byte a=1, b=2; byte c = a+b; // 編譯錯 | byte c = (byte)(a+b); |
| 物件包裝類拆箱空指針 | Integer x = null; int y = x; // NPE | 檢查 null 或用 Optional |
long/double 避免頻繁轉換。float/double,必須用 BigDecimal。long/double),內部再縮窄並驗證範圍。Byte.MIN_VALUE, Byte.MAX_VALUE, Short.MIN_VALUE...。