a = (a++) * (a++) gives strange results in Java [closed]
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);
Solution 1:
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)
Solution 2:
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.
Solution 3:
a++
means 'the value of a, and a is then incremented by 1'. So when you run
(a++) * (a++)
the first a++
is evaluated first, and produces the value 3. a
is then incremented by 1. The second a++
is then evaluated. a
produces the value of 4, and is then incremented again (but this doesn't matter now)
So this turns into
a = 3 * 4
which equals 12.