-1
class BlankIt{  
    public static void main(String[] args) {
        int i = 10, j = 20;
        while(i++ < --j){
            System.out.println("\n " + i + " " + j);
        }
        System.out.println("\n " + i + " " + j);
    }   
}

The preceding output is 16 14. Why is that happening?? The loop stops when the condition reaches 15 < 15. Please help me out!!

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 1
    You are comparing the value of `i` *before* increment with the value of `j` *after* decrement. So the comparisons are 10 < 19 (true), 11 < 18, 12 < 17, …, 14 < 15 (true) and 15 < 14 (false, causes loop to end). In the last comparison, `i` is incremented after the comparison, so the final values are 16 and 14. As you observed. – Ole V.V. Apr 15 '20 at 18:35
  • Please never use pre- or post-increment in a way where it actually matters, i.e. where you use its returned value. Try to always have it as a statement that is not used within another, in an explicit way. That way, no reader will be confused. – Zabuzard Apr 15 '20 at 22:54

1 Answers1

2

The increment of i, being a post-increment, will occur after the comparison is evaluated, j, on the other hand, being a pre-decrement will occur before the comparison is evaluated:

10 < 19 (true)
11 < 18 ...
12 < 17 ...
13 < 16 ...
14 < 15 ...
15 < 14 (false) 

After the evaluation of the last comparison, i will be incremented one more time and will have the value of 16, j since it was already decremented will remain 14.

anastaciu
  • 23,467
  • 7
  • 28
  • 53