Plat-Dev-201 practice question 13 of 30

Refer to the following Apex code: apex Copy Integer x = 0; do { x++; } while (x < 1); System.debug(x); What is the value of x when it is written to the debug log?

Full set: 204 questions
Answer options
A: 0
B: 2
C: 1 Correct answer
D: 3
Correct Answer:
C. 1
Explanation

The code initializes an integer x to 0. It then enters a do-while loop. The body of a do-while loop is always executed at least once before the condition is evaluated. Inside the loop, x is incremented to 1 (x++). After the first execution, the condition while (x < 1) is checked. Since x is now 1, the condition 1 < 1 evaluates to false, and the loop terminates. The final value of x, which is 1, is then written to the debug log.

Why Incorrect

A. 0: This would be the value if the loop body never executed, which is impossible for a do-while loop.
B. 2: This would be the value if the loop executed a second time, but the condition 1 < 1 is false, preventing a second iteration.
D. 3: This value is not reachable with the given loop condition and initialization.

References

1. Salesforce Developer Documentation, Apex Developer Guide, "Control Flow Statements", section "Do-While Loops". "A do-while loop first executes the code block once, and then it repeatedly executes the block...as long as a particular condition is true."

Scroll to Top