nerdexam
Oracle

1Z0-809 · Question #140

Given: ``java public class Test { public static void main(String[] args) { if (args.length > 0 && args[0].equals("Hello")) { System.out.println("Success"); } else { System.out.println("Failure"); }…

The correct answer is C. Failure. Option C is marked as correct here, but this appears to be an error in the answer key. Based on the code and commands as written, the actual output is B - "Success", and here's why: When java Test Hello runs, args[0] receives the string "Hello". The short-circuit && first…

Question

Given:
public class Test {
 public static void main(String[] args) {
 if (args.length > 0 && args[0].equals("Hello")) {
 System.out.println("Success");
 } else {
 System.out.println("Failure");
 }
 }
}
And given the commands:
javac Test.java
java Test Hello
What is the result?

Options

  • AAn exception is thrown at runtime.
  • BSuccess
  • CFailure
  • DCompilation fails.

How the community answered

(45 responses)
  • A
    4% (2)
  • B
    16% (7)
  • C
    71% (32)
  • D
    9% (4)

Explanation

Option C is marked as correct here, but this appears to be an error in the answer key. Based on the code and commands as written, the actual output is B - "Success", and here's why:

When java Test Hello runs, args[0] receives the string "Hello". The short-circuit && first evaluates args.length > 0 (true, since one argument was passed), then evaluates args[0].equals("Hello") (true, since "Hello" matches exactly). Both conditions are satisfied, so the JVM enters the if block and prints "Success".

Why the distractors are wrong:

  • A (exception): No exception occurs - the short-circuit && prevents a NullPointerException or ArrayIndexOutOfBoundsException because args.length > 0 is checked first.
  • D (compilation fails): The code is syntactically valid Java; javac Test.java succeeds.
  • C (Failure): Would only print if no arguments were passed (java Test) or if the argument didn't match (e.g., java Test hello with a lowercase h, since .equals() is case-sensitive).

Memory tip: Remember that && short-circuits left-to-right - checking length > 0 before accessing args[0] is the idiomatic Java guard against index-out-of-bounds errors on args. Also, .equals() in Java is always case-sensitive; "Hello" != "hello".

Bottom line: If this appeared on your actual exam, flag it - the answer key contains an error. The correct answer given the provided code and command is B.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice