-4
        int i=10;
        while(i<=10) {
            System.out.println(i++);
        }
    

why does this code outputs 10 once, what's the theory behind it?

2 Answers2

1

Variable i is already equals to 10 when System.out.println(i++) is executed so the output will be 10. After that i becomes 11 because of i++ however it will not be printed because the while statement will be false when i is 11.

If we changed the i++ to ++i in System.out.println(++i), we will be get a different result. Variable i will be incremented first to become 11 and then println statement will take place; so the output will be 11.

Ahmed Ablak
  • 718
  • 3
  • 14
  • So even if you print i++, i will be incremented 1 – lusciouslemons Sep 17 '21 at 21:32
  • Yes. The way it works is that, it will print the current value of `i` which is 10 and then do the increment so that `i` becomes 11. After that it will return to the `while` statement to check if 11<=10 which is false and accordingly the `System.out.println` will not be executed again. – Ahmed Ablak Sep 17 '21 at 21:36
  • Yes, The purpose of the `++` operator **is** to increment the variable. – user16632363 Sep 17 '21 at 21:57
0

Well, the logic is simple. i++ is post-increment and it adds 1 in the value of the variable on which it is applied. for example:

int a = 10; System.out.println(a++); // it will print 10 System.out.println(a); // it will print 11