Take a look at the following code:
class experiment{
public static void main(String[] args) {
int k = 3;
while (k-- > 0) {
System.out.println(k + "\n");
}
}
}
Expected output:
2
1
Actual output:
2
1
0
Postfix operators have higher precedence than operational operators. Hence k-- should be evaluated first before the k > 0, but looking at the output, k > 0 gets evaluated first. Do I miss something simple here?
Precedence has nothing to do with it. The value of ‘k–‘ is ‘k’. There is a side-effect of post-decrementing ‘k’ but it doesn’t affect the operand value.