1

can someone explain me the stack operations here

public static void main(String[] args) {
    int a=20;

    for(int i=1;i<10;i++) {
        a=a++;// why is the value of a unchanged here
        //System.out.println(i);
    }

    System.out.println(a);
}
  • Please read here https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java – KunLun Mar 20 '19 at 16:11
  • `a = a++` -> Means `a++` is execute and after will assign the original value of `a`. It's something like this `int b = a; -> a=a+1; -> a = b;`. That's how I see incrementing works. – KunLun Mar 20 '19 at 16:45

1 Answers1

0

The prefix increment returns the value of a variable after it has been incremented. On the other hand, postfix increment returns the value of a variable before it has been incremented.

That means when you say a = a++, it first returns the value of a and then increments it by 1. So, by the time of execution of the line print(i), a would have been incremented by 1.