This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
there is a problem..i am having a method in which .. int i=0; i=i++; System.out.println(i); it prints 0 instead of 1, its unlike C++..?? how this problem is actually linked with way of working of JVM, as regards JVM declares space in heap for variables..?? kindly clear my doubt..thanking u..
From the JLS Section.15.14.1 Postfix Increment Operator ++ :
At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (�5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (�5.1.3) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.
OK This sentence is the important one - remember it The value of the postfix increment expression is the value of the variable BEFORE the new value is stored.
So the code int i = 0; i = i++; Initial LHS is evaluated to i = 0 The postfix operator has a higher precedence than the assignment operator so it executes first and 'i' is set to '1' THEN the assignment ( = ) expression completes, it assigns the original value of 'i' ... the one BEFORE the postfix increment to the variable 'i', which in this case is once again '0'. Thus, the postfix value of 'i' is being OVERWRITTEN each time.
So when you write int i = 0; i = i++; --(1) i = i++; --(2) i = i++; --(3) System.out.println(i); 'i' will always evaluate to zero- every time. You can test this by changing your code sightly int i = 0; i++; i++; i++; System.out.println(i); This second example WILL print 3. Since this is a simple postfix increment the increment value is retained. The first example was a postfix increment ASSIGNMENT (assigning value back into the original) Hope this helps, regards. Jyotsna
Joined: May 29, 2001
thanks a lot jyotsna for ur so illustrative and wonderful replies!! i am satisfied with ur answers.
[This message has been edited by NIKHIL JAIN (edited May 30, 2001).]