Question:medium

What will be the output of the following Java program? verbatim class Output public static void main(String args[]) int arr[] = 1, 2, 3, 4, 5; for (int i = 0; i < arr.length - 2; ++i) System.out.println(arr[i] + " "); verbatim

Show Hint

Pay close attention to the loop termination condition. A common mistake is to misinterpret conditions like `i < length` versus `i <= length` or expressions like `length - 2`. Carefully trace the loop for the first and last valid index values.
Updated On: Jul 2, 2026
  • 1 2
  • 1 2 3
  • 1 2 3 4
  • 1 2 3 4 5
Show Solution

The Correct Option is B

Solution and Explanation

Step 1: Work out exactly how many times the loop runs.
The array arr holds 5 elements, so arr.length equals 5, and the loop condition i less than arr.length minus 2 becomes i less than 3, meaning i can only take the values 0, 1, and 2 before the condition fails.
Step 2: Map each surviving index to its stored value.
Index 0 holds 1, index 1 holds 2, and index 2 holds 3, since the array was filled in order as 1, 2, 3, 4, 5 when it was created.
Step 3: Read off the printed sequence.
The loop stops before it can ever reach index 3 or index 4, so only the first three elements are printed, giving the sequence 1, 2, 3 as shown in the matching option.
\[ \boxed{1\ 2\ 3} \]
Was this answer helpful?
0