I'm studying for the OCPJP exam, and so I have to understand every little strange detail of Java. This includes the order in which the pre- and post-increment operators apply to variables. The following code is giving me strange results:
int a = 3; a = (a++) * (a++); System.out.println(a); // 12
Shouldn't the answer be 11? Or maybe 13? But not 12!
FOLLOW UP:
What is the result of the following code?
int a = 3; a += (a++) * (a++); System.out.println(a);
After the first a++
a
becomes 4. So you have 3 * 4 = 12
.
(a
becomes 5 after the 2nd a++
, but that is discarded, because the assignment a =
overrides it)
Your statement:
a += (a++) * (a++);
is equivalent to any of those:
a = a*a + 2*a a = a*(a+2) a += a*(a+1)
Use any of those instead.
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