byte b1 = 1;
byte b2 = 2;
byte b3 = b1 + b2; // 編譯錯誤:incompatible types: possible lossy conversion from int to byte
Java 整數運算**自動提升至 `int`** 類型。`b1 + b2` 結果為 `int`,賦值給 `byte` 需顯式強轉,否則編譯器報「可能損失精度」錯誤(雖然實際值 3 在 byte 範圍內,編譯器只看類型)。
byte b3 = (byte)(b1 + b2); // 顯式強制轉型
// 或
int b3 = b1 + b2; // 接收為 int,避免轉型
防止隱式窄化轉換導致數據截斷(如 `byte b = 200; b = (byte)(b + 100);` 會溢出變為 -56)。強制程序員確認數值範圍安全後再轉型。
byte b = 1;
b += 2; // 編譯通過!等價於 b = (byte)(b + 2)
復合賦值運算符包含隱式強轉,是 Java 語言規定的特例。