nerdexam
Oracle

1Z0-809 · Question #138

Given the code fragment: ``java public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int i = 0; do { System.out.print(arr[i] + " "); i++; } while (i < arr.length - 1); } `` What is the…

The correct answer is C. 1 2 3. Option C is correct because the loop condition i < arr.length - 1 evaluates to i < 3, causing the loop to exit when i reaches 3 - after printing arr[0], arr[1], and arr[2] (values 1, 2, 3). The do-while body always executes at least once, so it prints 1 on the first pass, then…

Question

Given the code fragment:
public static void main(String[] args) {
 int[] arr = {1, 2, 3, 4};
 int i = 0;
 do {
 System.out.print(arr[i] + " ");
 i++;
 } while (i < arr.length - 1);
}
What is the result?

Options

  • ACompilation fails.
  • B1 2 3 4
  • C1 2 3
  • D1 2 3 4 followed by an ArrayIndexOutOfBoundsException

How the community answered

(40 responses)
  • A
    5% (2)
  • B
    8% (3)
  • C
    73% (29)
  • D
    15% (6)

Explanation

Option C is correct because the loop condition i < arr.length - 1 evaluates to i < 3, causing the loop to exit when i reaches 3 - after printing arr[0], arr[1], and arr[2] (values 1, 2, 3). The do-while body always executes at least once, so it prints 1 on the first pass, then 2 and 3 on subsequent passes, and stops before printing the fourth element.

A is wrong - the code is syntactically valid Java with no compilation errors. B is wrong - printing all four elements would require the condition i < arr.length (i.e., i < 4); the -1 cuts one iteration short. D is wrong - because the condition halts the loop before i ever reaches index 3 (the last valid index), so there is no out-of-bounds access.

Memory tip: Whenever you see arr.length - 1 as a loop bound, mentally substitute the number - here 4 - 1 = 3, so the loop runs while i < 3, meaning the last printed index is 2, not 3. Train yourself to count iterations, not just read the condition literally.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice