int i=10;
while(i<=10) {
System.out.println(i++);
}
why does this code outputs 10 once, what's the theory behind it?
int i=10;
while(i<=10) {
System.out.println(i++);
}
why does this code outputs 10 once, what's the theory behind it?
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.
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