In Java command-line arguments, what is printed by this program when executed as shown? public class Test { public static void main (String[] args) { String foo = args[1]; String bar = args[2]; String baz = args[3]; System.out.println("baz = " + baz); // Line 8 } } Invocation: > java Test red green blue
-
Abaz =
-
Bbaz = null
-
Cbaz = blue
-
DRuntime Exception
-
ENo output is produced
Answer
Correct Answer: Runtime Exception
Explanation
Introduction / Context: This question tests Java command-line argument indexing and what happens when you access an array element that does not exist. The code prints the value of args[3] after assigning several variables from the args array. Understanding zero-based indexing and the number of arguments passed is crucial.
Given Data / Assumptions:
- Program is executed with: java Test red green blue
- Therefore: args[0] = "red", args[1] = "green", args[2] = "blue"
- The code reads args[1], args[2], args[3]
Concept / Approach: Java arrays are zero-indexed. If the length is 3, valid indices are 0, 1, and 2. Any attempt to access args[3] when only three elements are present will throw ArrayIndexOutOfBoundsException at runtime. This occurs before the print statement executes, so no normal output line is printed.
Step-by-Step Solution:
Length of args = 3Read foo = args[1] → "green" (valid)Read bar = args[2] → "blue" (valid)Read baz = args[3] → index 3 out of bounds (invalid)Runtime throws ArrayIndexOutOfBoundsException; System.out.println is never reachedVerification / Alternative check: If the invocation had four tokens after the class name (e.g., java Test a b c d), then args[3] would be "d" and the print would succeed. The provided invocation has only three arguments.
Why Other Options Are Wrong:
- baz = or baz = null: No line prints because the exception occurs before printing.
- baz = blue: That would require
args[3]to exist; it does not. - No output is produced: While effectively true in terms of normal output, the precise outcome is a runtime exception, which is the most accurate choice.
Common Pitfalls: Forgetting zero-based indexing and assuming the first argument is args[1]; or assuming Java silently ignores out-of-range accesses (it does not).
Final Answer: Runtime Exception