Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
问题 :
char x = 'a'; x += 3; // ok x = x + 3; // compile time error
因为x += 3等价于x = (char)(x+3),而x + 3默认为int运算,分配一个 int 给 char 必须强制转换。
x += 3
x = (char)(x+3)
x + 3
int
从JLS specification : 15.26.2,
JLS specification : 15.26.2
E1 op= E2 形式的复合赋值表达式等价于 E1 = (T)((E1) op (E2)),其中 T 是 E1 的类型,除了 E1 只计算一次。请注意,隐含的类型 T 类型转换可能是恒等转换 (?.1.1) 或缩小原语转换 (?.1.3)。