Search code examples
javapost-incrementpre-incrementunary-operator

Post/Pre-Increment confusion


From what I understand, if I have a variable k = 5, and I do ++k, the new value of k = 6. If I do k++, the value remains 5 until k appears the second time in the program, which is when it is changed to 6. For e.g:

k = 5;
System.out.println(k++); //prints 5, but now that k has appeared the second time, its value is incremented to 6
System.out.println(k); //prints 6

However, in this code:

class test {
    public static void main(String args[]){
        for(int i =0; i<10; i++){
            System.out.println(i);
        }
        int x = 0;
        x++;
        System.out.println(x);
    }
}

Output:

0
1
2
3
4
5
6
7
8
9
1

In the loop, though the variable i appears for the 2nd time(in System.out.println(i)), its value remains at 0. But for x, when it appears for the second time( in System.out.println(x); ) its value is incremented. Why? I'm confused about how post and pre-increment work.


Solution

  • For your code

        for(int i =0; i<10; i++){
            System.out.println(i);
        }
    

    firstly the variable i is initialized to 0, it then checks if it satisfies the condition i < 10 and print the variable and lastly increments the variable i.

    This is how the for loop works.

    In the second piece of code you have written, it increments the variable x and lastly prints the value of x.