nerdexam
Oracle

1Z0-809 · Question #106

Given the code fragment: ``java int [] lst = {1, 2, 3, 4, 5, 3, 2, 1}; int sum = 0; for (int frnt = 0, rear = lst.length - 1; frnt < 5 && rear >= 0; frnt++, rear--) { sum = sum + lst[frnt] +…

The correct answer is A. 20. Tracing through this code carefully reveals a discrepancy with the stated answer key - the code as written actually outputs 30, not 20. Step-by-step trace: The array {1, 2, 3, 4, 5, 3, 2, 1} has 8 elements (indices 0–7), so rear starts at 7. The loop runs while frnt < 5 && rear…

Question

Given the code fragment:
int [] lst = {1, 2, 3, 4, 5, 3, 2, 1};
int sum = 0;
for (int frnt = 0, rear = lst.length - 1;
 frnt < 5 && rear >= 0;
 frnt++, rear--) {
 sum = sum + lst[frnt] + lst[rear];
}
System.out.print(sum);
What is the result?

Options

  • A20
  • B25
  • C29
  • DCompilation fails
  • EAnArrayIndexOutOfBoundsException is thrown at runtime

How the community answered

(32 responses)
  • A
    78% (25)
  • B
    13% (4)
  • C
    3% (1)
  • D
    6% (2)

Explanation

Tracing through this code carefully reveals a discrepancy with the stated answer key - the code as written actually outputs 30, not 20.

Step-by-step trace:

The array {1, 2, 3, 4, 5, 3, 2, 1} has 8 elements (indices 0–7), so rear starts at 7. The loop runs while frnt < 5 && rear >= 0, yielding 5 iterations:

frntrearlst[frnt] + lst[rear]sum
071 + 1 = 22
162 + 2 = 46
253 + 3 = 612
344 + 5 = 921
435 + 4 = 930

At frnt = 5, the condition 5 < 5 is false and the loop exits. System.out.print(sum) prints 30.

Why the distractors are wrong:

  • D (Compilation fails): The code is syntactically valid - declaring two variables in the for-init with the same type is legal Java.
  • E (ArrayIndexOutOfBoundsException): All accesses are safe. frnt reaches at most 4 and rear reaches at minimum 3, both valid indices for an 8-element array.
  • B (25) and C (29): Neither matches any plausible misreading of the iteration.

Assessment: The stated correct answer of A (20) appears to be an error in the answer key. The answer would be 20 if the original question used a 7-element palindrome {1, 2, 3, 4, 3, 2, 1} with a frnt < rear condition - a likely source of the mistake. As written, the code prints 30.

Memory tip: In two-pointer loops, always check both termination conditions and trace all the way through - especially when the two pointers can "cross" and still satisfy the condition (as frnt=4, rear=3 does here).

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice