0
Could anybody explain why j = - 2 in this code? (Java)
public class Program { public static void main(String[] args) { int i = 0, j = 0, k = 0; while(i < 2) { j = i++; System.out.println("step 1 i = " + i); System.out.println("step 1 j = " + j); while(j-- >= 0) k = k + ((j % 2 == 0) ? -1 : 1); System.out.println("step 2 j = " + j); System.out.println("step 2 k = " + k); } System.out.println("final i = " + i); System.out.println("final j = " + j); System.out.println("final k = " + k); } } Output step 1 i = 1 step 1 j = 0 step 2 j = - 2 step 2 k = 1 step 1 i = 2 step 1 j = 1 step 2 j = - 2 step 2 k = 1 final i = 2 final j = - 2 final k = 1
1 ответ
+ 4
That's because of postfix decrement.
Let's say after some iterations j = 0
the condition will be checked
0 >= 0, (True)
j--; ---> j = -1
As condition is true, compiler will get inside the loop and condition will be checked again
1 >= 0, (False)
j--; ---> j = -2
Now condition is false, loop will be terminated. And final value of j is -2.