Java arrays and command-line arguments: populating a larger array from args and printing names[2].\n\npublic class X {\n public static void main(String[] args) {\n String[] names = new String[5];\n for (int x = 0; x < args.length; x++)\n names[x] = args[x];\n System.out.println(names[2]);\n }\n}\n// Invocation: > java X a b

Difficulty: Easy

Correct Answer: null

Explanation:


Introduction / Context:
This question tests understanding of default array initialization and bounds when partially populating an array from the command line. The code assigns only as many elements as args provides, then prints the element at index 2.



Given Data / Assumptions:

  • args = {"a", "b"} → args.length = 2.
  • names = new String[5] initializes all elements to null by default.
  • Loop assigns names[0] = "a", names[1] = "b"; indices beyond 1 remain null.


Concept / Approach:
Printing names[2] after copying only two arguments should yield null since names[2] was not assigned any value and remains at its default reference value.



Step-by-Step Solution:

Create names array of length 5 → all entries null.Copy args: indices 0 and 1 become "a" and "b".names[2] is still null → println prints "null".


Verification / Alternative check:
If the invocation were > java X a b c, names[2] would print c. With no args, names[0] would also be null.



Why Other Options Are Wrong:

  • names: Never assigned to names[2].
  • Compilation fails: Code is valid.
  • Exception: Access is within bounds; null is printable.
  • Empty line: println prints the string literal "null" for a null reference.


Common Pitfalls:
Confusing default null with an empty string, or thinking println throws when printing null.



Final Answer:
null

More Questions from Language Fundamentals

Discussion & Comments

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