Is:
x -= y;
equivalent to:
x = x - y;
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.
No, they are NOT equivalent the way you expressed them.
The problem with the third line is that
-performs what is called “numeric promotion” (JLS 5.6) of theshortoperands, and results in anintvalue, which cannot simply be assigned to ashortwithout a cast. Compound assignment operators contain a hidden cast!The exact equivalence is laid out in JLS 15.26.2 Compound Assignment Operators:
So to clarify some of the subtleties:
int x = 5; x *= 2 + 1; // x == 15, not 11int i = 0; i += 3.14159; // this compiles fine!arr[i++] += 5; // this only increments i onceJava also has
*=,/=,%=,+=,-=,<<=,>>=,>>>=,&=,^=and|=. The last 3 are also defined for booleans (JLS 15.22.2 Boolean Logical Operators).Related questions