Java command-line arguments and array bounds: trace the loop and identify the runtime behavior.\n\npublic class CommandArgsTwo {\n public static void main(String[] argh) {\n int x;\n x = argh.length; // number of arguments\n for (int y = 1; y <= x; y++) {\n System.out.print(" " + argh[y]); // note: starts at 1 and uses <=\n }\n }\n}\n// Invocation: > java CommandArgsTwo 1 2 3

Difficulty: Easy

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

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion