Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of pre/post increment operators in Multiplication scenarios [duplicate]

Tags:

java

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.
like image 416
user1500024 Avatar asked Nov 29 '22 02:11

user1500024


2 Answers

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.

like image 22
nhahtdh Avatar answered Dec 04 '22 17:12

nhahtdh


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

like image 66
ioreskovic Avatar answered Dec 04 '22 17:12

ioreskovic