Java command-line arguments indexing: determine what prints and whether an exception occurs.\n\npublic class CommandArgs {\n public static void main(String[] args) {\n String s1 = args[1];\n String s2 = args[2];\n String s3 = args[3];\n String s4 = args[4]; // potential out-of-bounds\n System.out.print(" args[2] = " + s2);\n }\n}\n// Invocation: > java CommandArgs 1 2 3 4

Difficulty: Easy

Correct Answer: An exception is thrown at runtime.

Explanation:


Introduction / Context:
This program highlights array bounds and evaluation order in Java. Even though the final print references s2, the statements assigning s1…s4 execute sequentially first. If any assignment throws an exception, the print is never reached.



Given Data / Assumptions:

  • args supplied: {"1", "2", "3", "4"}.
  • Valid indices: 0..3 for four elements.
  • Code attempts to access args[4].


Concept / Approach:
Accessing args[4] with only four elements triggers ArrayIndexOutOfBoundsException. This happens before the System.out.print call, so nothing is printed successfully.



Step-by-Step Solution:

s1 = args[1] → "2" (valid).s2 = args[2] → "3" (valid).s3 = args[3] → "4" (valid).s4 = args[4] → throws ArrayIndexOutOfBoundsException.Program aborts; print statement is not executed.


Verification / Alternative check:
Removing the s4 line or guarding with if (args.length > 4) would allow the print “ args[2] = 3”.



Why Other Options Are Wrong:

  • args[2] = 2 / 3 / null: Would require reaching the print; the exception prevents it.
  • Empty output: While nothing is printed, the precise reason is a runtime exception, which is the correct diagnostic choice.


Common Pitfalls:
Forgetting that args is zero-based; assuming later statements are skipped even when earlier ones fail.



Final Answer:
An exception is thrown at runtime.

Discussion & Comments

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