The important thing to know is that x++ is using the postfix ++ operator, not the prefix ++ operator, so the incrementing will be done after the expression evaluates to 0.
First, the operands x++ and y get evaluated. x was 0 before this line, so x++ evaluates to 0 and then increments the value of x to 1. y evaluates to 0. So the right-hand side of the assignment operator (=) evaluates to (0 + 0), which evaluates to 0. Then x (which was set to 1 for a moment) gets assigned that 0 value because of the = operator. So at the end of the statement, x gets assigned the value 0.
So ask yourself this: Why does Java interpret x+++y as (x++)+y rather than x+(++y)?
the answer is simple.... java starts parsing the expression from left to right so whenever it gets x++ it puts as (x++)and then looks for other operator if next operator is +y (like x+++y) then it assing next expresion as +y
but if it get expression as (x++++y) (four plus) it add the same way i explain above but as in this case it didn't get ++operatoer to join with y it do like this ( x++ + (+y))
but in x=x+++++y; in this case it gets increment operator (++y) so it puts like x = (x++) + (++y);
hope i clear it.....
one more thing the expresion +-+-+-+-+1 or +-+-+-+-+x ? any idea
guesss.... i got conused when i see code i thought it will give compiler error but it gets compiled... it works as from left to right with methamatics +-=- -+=- ++=+ --=+
so the expresion get solve from left to rt. with respected calculation so
+-+-+-+-+1 = +1
hope it helps....
now the final conculsion for code like this int x = 0; int y = 0; x = x++ + y;
i think we have to remember that
final result will have seprate calculation memory area and for primitve other one... final result will always be assinged at last
as fred explain like this
the first thing we do is figure out what x and y are. they are both 0. add them together, you get 0.
now, increment x. x = 1.
now assign the result of your computation to x.
here final result is assinged at last after primitive increment which is overided by final result...
Originally posted by amit taneja: ... x = x+++++y; x = ((x++)++)+y; //this is right or x = (x++)+(++y); // this is right ...
Based on the similar compilation errors, it appears that x+++++y is being interpreted as ((x++)++)+y. Unfortunately, I can't explain exactly why.
Note that section 15.7.2 of the Java Language Specification states, "The Java programming language also guarantees that every operand of an operator ... appears to be fully evaluated before any part of the operation itself is performed."
From this, one might reason that Java tries to associate with the left operand as many unary operators as possible from left to right before interpreting a binary operator. So x is followed by a unary ++, and then another ++ before the binary +.
I hope someone with more expertise is able to clarify. [ June 13, 2005: Message edited by: marc weber ]