+= operator with String and casted char

Viewed 205

This may be a stupid question, but I found an interaction that I cannot understand. I think it has to do with how += works.

String temp = "";
temp += (char) 90 + 10;
System.out.println(temp); // "100"
temp = "" + (char) 90 + 10;
System.out.println(temp); // "Z10"

Z10 makes sense. 100 does not. I would think the second line would execute in one of two different ways to produce "Z10" or "d". Why does the casting seemingly get ignored?

3 Answers

It has nothing to do with +=. It is to do with how + works.

If either of the operands of + is of String type, + is the string concatenation operator; otherwise, it is numeric addition.


temp += (char) 90 + 10; 

is the same as

temp += ((char) 90 + 10);

So the bracket is evaluated first, and then the += is applied. Here, neither (char) 90 nor 10 are Strings, so + is numeric addition.

In order to do numeric addition, the two operands must be made compatible - this is called binary numeric promotion. If the operands are a char and an int, the char is widened to an int.

Hence (char) 90 is immediately widened back to 90; then the two ints can be added - yielding 100 - and then that can be appended to the temp String via +=.


On the other hand

temp += "" + (char) 90 + 10;

is the same as

temp += (("" + (char) 90) + 10);

So, it evaluates the inner-most brackets first.

Because "" is a String, "" + (char) 90 is string concatenation, resulting in the value "Z". That's a String too; so "Z" + 10 is also string concatenation, resulting in "Z10".

Assignment operators such as += have the lowest precedence, and therefore += is evaluated after +.

Hence, before the += operator is evaluated, its 2 operands are evaluated. The first operand is temp and the second operand is (char) 90 + 10. (char) 90 + 10 evaluates to 100 (two numeric operands, so + performs addition). Therefore 100 is concatenated to the empty String referenced by temp, resulting in the String "100".

On the other hand, in

temp = "" + (char) 90 + 10;

there are two + operators. Both have the same precedence, so they are evaluated from left to right.

  • First "" + (char) 90 performs concatenation of a String and a char, resulting in a String whose single character is the character matching the value 90 ("Z").

  • Then the second + concatenates the int 10 to the String "Z", resulting in the String "Z10".

Type casting has higher precedence than arithmetic operators.

(char) 90 + 10 is evaluated as ((char) 90) + (10). The result of adding a char to an int is an int.

What you want instead is (char) (90 + 10), i.e. cast the result of the addition to a char. Then it will be appended to the String as a char:

    String temp = "";
    temp += (char) (90 + 10);
    System.out.println(temp); // prints "d"
Related