nerdexam
Oracle

1Z0-819 · Question #169

public class Myclass { public static void main(String[] args) { System.out.println(arg[1] + "--" + arg[3] + "--" + arg[0]); } } executed using this command: java Myclass My Car Is Red What is the…

The correct answer is A. Car-red-My. Option A is correct because when you run java Myclass My Car Is Red, the JVM populates the args array starting at index 0 with the arguments after the class name: args[0]="My", args[1]="Car", args[2]="Is", args[3]="Red". The print statement outputs args[1], then args[3], then…

Working with Arrays and Collections

Question

public class Myclass { public static void main(String[] args) { System.out.println(arg[1] + "--" + arg[3] + "--" + arg[0]); } } executed using this command: java Myclass My Car Is Red What is the output of this class?

Options

  • ACar-red-My
  • BMy-Car-is
  • CMy-Car-Red
  • DJava-My-Isis-My
  • EMyclass-Car-red

How the community answered

(32 responses)
  • A
    69% (22)
  • B
    16% (5)
  • C
    3% (1)
  • D
    9% (3)
  • E
    3% (1)

Explanation

Option A is correct because when you run java Myclass My Car Is Red, the JVM populates the args array starting at index 0 with the arguments after the class name: args[0]="My", args[1]="Car", args[2]="Is", args[3]="Red". The print statement outputs args[1], then args[3], then args[0] - giving Car--Red--My (the hyphens in option A represent the "--" separator).

Why the distractors are wrong:

  • B (My-Car-is) follows the order [0][1][2], ignoring that the code skips index 2 entirely.
  • C (My-Car-Red) follows the order [0][1][3], but the code clearly starts with arg[1], not arg[0].
  • D is a nonsense distractor - "Java" and "Isis" don't appear anywhere in the argument list.
  • E confuses the class name Myclass with a command-line argument; the class name is never stored in args[].

Memory tip: Think of args[] as a 0-indexed list of everything you type after the class name. "Java" and the class name (Myclass) are never in the array - only the words that follow it are. When you see a print that mixes index order (e.g., [1], [3], [0]), mentally replace each index with its word before choosing an answer.

Note: The code as written uses arg (no s), which would cause a compile error. This is almost certainly a typo in the question; the intended variable is args.

Topics

#command-line arguments#array indexing#string concatenation#args array

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice