Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior Java += operator

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 ?

like image 725
confucius Avatar asked Feb 07 '12 18:02

confucius


4 Answers

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".

like image 70
NPE Avatar answered Oct 07 '22 22:10

NPE


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.)

like image 33
Hauke Ingmar Schmidt Avatar answered Oct 07 '22 22:10

Hauke Ingmar Schmidt


This is all about operator associativity.

str += ((char)97) +2;

Would translate to:

str = str + ( ((char)97)+2 );
like image 39
kaoD Avatar answered Oct 07 '22 22:10

kaoD


Your first line is equivalent to:

str = str + ((char)97) + 2);

while your second one is equivalent to:

str = (str + ((char)97)) + 2
like image 33
Herms Avatar answered Oct 07 '22 22:10

Herms