Post Increment Issue in Java

why the below code in java outputs 10 and not 13.

int i=10;
i=i++;
i=i++;
i=i++;
System.out.println(i);


Because, In Java variables are stored on 2 places, Array and Stack.
Lets understand the below statement, consider i=5.

i=i++;

Since, its a post-increment, first the assignment will happen and then the value will be incremented.
So, value of i at L.H.S got value 5. And stores into the Stack.
Now, the value of i at R.H.S got incremented by 1 so it is now 6. And stores the incremented value in Array.

Now, when you say; 


System.out.println(i);

the value from the stack is printed, which is 5 and not 6.

Hence Proved :-P

Comments

Popular posts from this blog

Hashicorp Configuration Language - HCL

Terraform - Input Variables

Terraform - Tainting and Updating Resources