Possible Duplicate:
Is there a difference between x++ and ++x in java?
Can anyone please explain me what is happening backyard to these statements?
int x=5;
System.out.println((x++)*x); //Gives output as 30
int x=5;
System.out.println((++x)*x); //Gives output as 36.
Multiplication is left-to-right associative, so the left operand will be evaluated first, then the right operand.
Post-increment operator will evaluate to current value of the variable, and increment it right after.
Pre-increment operator will increment the variable, then evaluate to the incremented value.
(x++) * x (x = 5)
--> 5 * x (increment deferred, x = 5)
--> 5 * x (increment x, x = 6)
--> 5 * 6
--> 30
(++x) * x (x = 5)
--> 6 * x (x is incremented before evaluated into expression, x = 6)
--> 6 * 6
--> 36
I mentioned the associativity here because it will affect the final result. If the associativity of multiplication is right-to-left instead of left-to-right, then the result will be 25 and 30 for post-increment and pre-increment expression respectively.
int x=5;
System.out.println((x++)*x); //Gives output as 30
You first take x (x = 5) as an operand. Then it's incremented to 6 which is second operand.
int x=5;
System.out.println((++x)*x); //Gives output as 36.
You first increment x by one (x = 6) and then multiply by x => 6 * 6 = 36
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