Please see the code below. The code runs and displays 0 as output, even though the Print command is called after the line x = x++; have executed completely. I was expecting 1 as output. Please help... //LangSpecs.java public class LangSpecs { public static void main(String[] args) { int x = 0; x = x++; System.out.println("Value of x is : " +x); } }
Guess it is because the ++ operator has precedence over the assignment operator. The operation in the code would be performed in the following sequence : Increments op by 1; evaluates to the value of op before it was incremented So, if the assignment is made to the same variable the change is overridden. But, if the assignment y = x++ would work as expected by you.
Change the postfix operator to prefix operator and try it. That will give you a clue about what's going on. Basically, 1. Operands are evaluated from left to right, and the operations are performed in the order of precedence and associativity. 2. ++ operator is one of the operators which are very high in the precedence level. = is one of the lowest. Hope this helps.