Java command-line arguments and array bounds: trace the loop and identify the runtime behavior. public class CommandArgsTwo { public static void main(String[] argh) { int x; x = argh.length; // number of arguments for (int y = 1; y <= x; y++) { System.out.print(" " + argh[y]); // note: starts at 1 and uses <= } } } // Invocation: > java CommandArgsTwo 1 2 3
-
A0 1 2
-
B1 2 3
-
C0 0 0
-
DAn exception is thrown at runtime
-
EEmpty output
Answer
Correct Answer: An exception is thrown at runtime
Explanation
Introduction / Context: This item tests array indexing rules with command-line arguments. Java arrays are zero-based. Accessing an element at index length results in ArrayIndexOutOfBoundsException. Also, starting at index 1 skips the first element.
Given Data / Assumptions:
- argh = {"1", "2", "3"}; argh.length = 3.
- Loop: y runs from 1 to x (inclusive).
- Body accesses argh[y].
Concept / Approach: Legal indices are 0, 1, 2. The loop attempts to access argh[3] on the final iteration, which is out of bounds, causing a runtime exception before the loop completes.
Step-by-Step Solution:
y = 1 → prints argh[1] = "2".y = 2 → prints argh[2] = "3".y = 3 → tries argh[3] → throws ArrayIndexOutOfBoundsException.Verification / Alternative check: Correct code would use for (int y = 0; y < x; y++) System.out.print(" " + argh[y]); which prints “ 1 2 3”.
Why Other Options Are Wrong:
- Numeric outputs assume the loop completed successfully.
- Empty output: Not the case; an exception occurs mid-loop.
Common Pitfalls: Off-by-one errors are a classic source of runtime faults when iterating arrays with inclusive bounds.
Final Answer: An exception is thrown at runtime