Can anyone explain this to me ,
String str = "Hello";
str += ((char)97) +2; // str = "Hello99";
str = str +((char)97)+2; // str = "Helloa2";
does the +=
operator evaluate the right side first then it concatenate it with the left side ?
The difference has to do with the order of operations. The following:
str += ((char)97) +2;
is equivalent to:
str = str + (((char)97) + 2);
On the other hand, the following:
str = str +((char)97)+2;
is equivalent to:
str = (str + ((char)97)) + 2;
Note the difference in the placement of parentheses.
Now let's consider the two cases:
1) str = str + (((char)97) + 2)
:
Here, 97 + 2
is evaluated first. The result is an int
(99
), which is converted to string and appended to str
. The result is "Hello99"
.
2) str = (str + ((char)97)) + 2
:
Here, (char)97
('a'
) is appended to the string, and then 2
is converted to string and appended to the result. This gives "Helloa2"
.
Yes. The relevant section of the JLS is here: http://java.sun.com/docs/books/jls/first_edition/html/15.doc.html#5304
At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:
- First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
- Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
- Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see §15.16.2), then the assignment expression completes abruptly for the same reason and no assignment occurs.
- Otherwise, the result of the binary operation is converted to the type of the left-hand variable and the result of the conversion is stored into the variable.
(Emphasis by me.)
This is all about operator associativity.
str += ((char)97) +2;
Would translate to:
str = str + ( ((char)97)+2 );
Your first line is equivalent to:
str = str + ((char)97) + 2);
while your second one is equivalent to:
str = (str + ((char)97)) + 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With