Concatenation of Strings and characters

后端 未结 5 1763
日久生厌
日久生厌 2020-12-24 10:46

The following statements,

String string = \"string\";   

string = string +((char)65) + 5;
System.out.println(string);

Produce the output <

5条回答
  •  暖寄归人
    2020-12-24 11:21

    You see this behavior as a result of the combination of operator precedence and string conversion.

    JLS 15.18.1 states:

    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.

    Therefore the right hand operands in your first expression are implicitly converted to string: string = string + ((char)65) + 5;

    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.

提交回复
热议问题