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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The difference has to do with the order of operations. The following:
is equivalent to:
On the other hand, the following:
is equivalent to:
Note the difference in the placement of parentheses.
Now let’s consider the two cases:
1)
str = str + (((char)97) + 2):Here,
97 + 2is evaluated first. The result is anint(99), which is converted to string and appended tostr. The result is"Hello99".2)
str = (str + ((char)97)) + 2:Here,
(char)97('a') is appended to the string, and then2is converted to string and appended to the result. This gives"Helloa2".