Practice Question to help understand the difference between i++ and ++i

Practice Question, Oracle Certified Associate: Java SE8 Programming (1Z0-808)

In this example, I will be going through an example of a Java SE Programming certification test.
The topic is integer increment- and decrements using i++ and ++i.

Q: What will the output be after code execution?

public class Demo {
    public static void main(String[] args) {
        int i = 0;
        int j = 6;
        do {
            if (i++ > --j) {
                continue;
            }
        } while (i < 3);
        System.out.println("i: " + i + ", j: " + j);
    }
}

Choose one answer:

  • a) i: 2, j: 3
  • b) i: 3, j: 2
  • c) i: 3, j: 3
  • d) i: 4, j: 2
  • e) i: 4, j: 3

 

 

 

 

Click here to view answer

The answer is c).

Why?
The difference between i++ and –j when used inside a condition is that i++ increments after the condition has been checked, and –j is decreased before the condition is being checked.

Initial values: int i=0, j=6.
#1 Condition check if(0++ > –6) is the equivalent of if(0 > 5). After the condition, i=1, j=5.
#2 Condition check if(1++ > –5) is the equivalent of if(1 > 4). After the condition, i=2, j=4.’
#3 Condition check if(2++ > –4) is the equivalent of if(2 > 3). After the condition, i=3, j=3.
#3 is when we jump out of the do-while loop, since while(3 < 3) is false, resulting in the final values i=3 and j=3.

 

 

 

A recommended source for material to help you prepare for the certification exam can be found in Oracle’s web-site.