Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# increment post and pre, when used in println

Sekhar Choudary
Ranch Hand
Posts: 57
Hi ,

Can anyone explain lines 1, 2, 3 and 4 and differences.
Thanks.

Ankit Garg
Sheriff
Posts: 9509
22
Lets go through the execution step by step

int x=2;
int y=1;

System.out.println(y+++x);
This will be interpreted as ((y++)+x) This is because the compiler will parse the expression from left to right. postfix ++ operator is left associative so first two + out of +++ will be associated with y. the one + left will be a binary operator between y++ and x.
But the output will be 3 as it will be interpreted as 1+2. This is because the value of y will be 1 in this expression. After using the value of y in the expression y will be incremented.

Now x = 2 and y = 2
System.out.println(y+ ++x);
This one is simple. It will work as 2+3. Here the value of x will be first incremented and then used in the expression.

Now x = 3 and y = 2
System.out.println(++x);
This one is again easy. The value of x will be incremented from 3 to 4 and then displayed.

Now x = 4 and y = 2
System.out.println(x++);
In this one the value of x will be used in the expression and then incremented. So 4 will be displayed and then the value of x will become 5.

I think you have confusion between pre and postfix increment operators. Consult some book for this or google it...

Mario Razec
Greenhorn
Posts: 17
Hi SekBar prefix and postfix is strange =)
Ankit excellent explanation...

Remember: The book (K&B)pg:289: "The operator is placed either before (prefix) or after (postfix) a variable to change its value."

I advise the Debug Code for greater understanding.
Look: http://www.janeg.ca/scjp/oper/prefix.html

Sekhar Choudary
Ranch Hand
Posts: 57
Thank you guys.
Sekhar.