我编写了两个版本的 Java 代码来将 char 变量递增 1:
版本1:
char c = 'a';
c = c + 1;
版本2:
char c = 'a';
c += 1;
令我惊讶的是,第二个版本编译并成功运行,但第一个版本显示错误,指出不兼容的类型:从 int 到 char 的有损转换。为什么它们不同?
最佳答案
第二个版本涉及强制转换,相当于:
c = (char) (c + 1);
参见JLS section 15.26.2 (复合运算符):
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, where T is the type of E1, except that E1 is evaluated only once.
关于java - 将 char 变量增加 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374896/