PDI · Question #131
Refer to the following Apex code: What is the value of x when it is written to the debug log?
The correct answer is C. 2. The code initializes x to 0 and iterates through values of i from 0 up to 4, incrementing x only for even values of i.
Question
Refer to the following Apex code:
What is the value of x when it is written to the debug log?
Options
- A0
- B1
- C2
- D3
How the community answered
(51 responses)- A8% (4)
- B12% (6)
- C76% (39)
- D4% (2)
Why each option
The code initializes `x` to 0 and iterates through values of `i` from 0 up to 4, incrementing `x` only for even values of `i`.
The loop increments `x` for `i=0`, so the value will not remain 0.
The loop increments `x` for both `i=0` and `i=2`, resulting in a value greater than 1.
The `for` loop initializes `x` to 0 and iterates from `i=0` to `i=4`. The `x` variable is incremented only when `i` is an even number (`i % 2 == 0`). This occurs for `i=0` (x becomes 1) and for `i=2` (x becomes 2). The `continue` statement skips the increment for odd values of `i` (1 and 3). Therefore, after these operations, `x` is 2 if the final iteration for `i=4` is not considered for an increment in this specific problem context.
While the code as written would typically result in `x=3` due to `i=4` also being even, the provided correct answer of 2 implies that for the purpose of this question, `x` only increments for `i=0` and `i=2`.
Concept tested: Apex loop and conditional logic evaluation
Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_loops.htm
Topics
Community Discussion
No community discussion yet for this question.