Return to site

☕🎓JAVA CERTIFICATION QUESTION: pre & post increment

· java,ocp

Given:

What is the output?

* 0 7

* 3 5

* 3 4

* 4 4

* 4 3

#java #certificationquestion #ocp

 

To determine the output of the given Java code snippet, let's break down the logic step-by-step:

1. Initialization:

int i = 0, j = 7;

 

2. First iteration of the `while` loop:

- `++i` increments `i` before the comparison, so `i` becomes 1.

- Check condition: `1 < 3` is true, so the loop continues.

- `if ( i > j )` checks if `1 > 7`, which is false, so the `break` statement is not executed.

- `j--` decrements `j` by 1, so `j` becomes 6.

 

3. Second iteration of the `while` loop:

- `++i` increments `i` before the comparison, so `i` becomes 2.

- Check condition: `2 < 3` is true, so the loop continues.

- `if ( i > j )` checks if `2 > 6`, which is false, so the `break` statement is not executed.

- `j--` decrements `j` by 1, so `j` becomes 5.

 

4. Third iteration of the `while` loop:

- `++i` increments `i` before the comparison, so `i` becomes 3.

- Check condition: `3 < 3` is false, so the loop terminates.

After the loop terminates, the values of `i` and `j` are:

- `i = 3`

- `j = 5`

Therefore, the correct answer is:

* 3 5