nerdexam
Oracle

1Z0-819 · Question #159

public class Main { public static public static void main(String[] args) { int i = 1; for(String s : args) { System.out.println((i++) + " " + s); } } } executed with this command: java Main one two…

The correct answer is E. 1one 2two 3three. Looking at this question carefully, I need to flag an issue before explaining. The stated answer (E) appears to be incorrect - and so does E's output format. Here's why: The code has a duplicate modifier: public static public static void main(...) - Java does not allow the same…

Controlling Program Flow

Question

public class Main { public static public static void main(String[] args) { int i = 1; for(String s : args) { System.out.println((i++) + " " + s); } } } executed with this command: java Main one two three What is the output of this class?

Options

  • AThe compilation fails.
  • BThe program throws a ClassCastException.
  • CA java.lang.ArrayIndexOutOfBoundsException is thrown.
  • D1 one
  • E1one 2two 3three

How the community answered

(56 responses)
  • A
    4% (2)
  • B
    7% (4)
  • C
    14% (8)
  • D
    2% (1)
  • E
    73% (41)

Explanation

Looking at this question carefully, I need to flag an issue before explaining.

The stated answer (E) appears to be incorrect - and so does E's output format.

Here's why:

The code has a duplicate modifier: public static public static void main(...) - Java does not allow the same modifier to appear more than once on a declaration. This is a compile-time error, making A the actual correct answer.

Additionally, even if we fix the duplicate modifier, the expression (i++) + " " + s would produce "1 one", "2 two", "3 three" - with spaces - because when a String operand appears in a + chain, Java performs string concatenation. That would make D the closer answer, not E.


Summary of the distractors (assuming fixed code):

ChoiceWhy wrong
AWould be correct as-written, but assuming fixed code - no compile error
BClassCastException requires an invalid cast; none exists here
CArrayIndexOutOfBoundsException - the enhanced for loop handles bounds safely
DClosest to correct if the code compiled - output has spaces
EMissing the spaces between number and word

Memory tip: When you see duplicate modifiers (e.g., public public, static static), Java always fails to compile - it's a JLS rule that a modifier cannot appear more than once in a declaration. Flag it immediately on exams.

Bottom line: This question likely contains a typo in the answer key. Based on the code as written, A (compilation fails) is the defensible correct answer.

Topics

#post-increment operator#enhanced for-each loop#string concatenation#loop semantics

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice