字符串和字符的连接 [英] Concatenation of Strings and characters
问题描述
以下陈述,
String string = "string";
string = string +((char)65) + 5;
System.out.println(string);
产生输出 stringA5
。
但是,
String string = "string";
string += ((char)65) + 5;
System.out.println(string);
生成 string70
。
区别在哪里?
推荐答案
您看到这种行为是因为这种结合运算符优先级和字符串转换。
You see this behavior as a result of the combination of operator precedence and string conversion.
JLS 15.18.1 陈述:
如果只有一个操作数表达式是String类型,然后在另一个操作数上执行字符串转换(第5.1.11节)以在运行时生成一个字符串。
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
因此,第一个表达式中的右手操作数被隐式转换为字符串: string = string +((char)65)+ 5;
Therefore the right hand operands in your first expression are implicitly converted to string: string = string + ((char)65) + 5;
对于第二个表达式但是 string + =((char)65)+ 5;
+ =
复合赋值运算符必须与 +
一起考虑。由于 + =
弱于 +
, +
运算符首先评估。我们有一个 char
和一个 int ,它会产生二进制数字促销到 int
。只评估 + =
,但此时已经评估了涉及 +
运算符的表达式的结果。
For the second expression however string += ((char)65) + 5;
the +=
compound assignment operator has to be considered along with +
. Since +=
is weaker than +
, the +
operator is evaluated first. There we have a char
and an int which results in a binary numeric promotion to int
. Only then +=
is evaluated, but at this time the result of the expression involving the +
operator has already been evaluated.
这篇关于字符串和字符的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!