nerdexam
Oracle

1Z0-819 · Question #11

Which two method implementations are correct, when inserted independently in line 1? (Choose two.)

The correct answer is A. public boolean methodD(int x) { return x > 0; } E. public void methodA() { System.out.println("methodA"); }. Options A and E are correct because they both honor the contract between the declared return type and what the method actually returns. Option A declares boolean and returns x > 0, which is a valid boolean expression. Option E declares void and has no return statement - void…

Java Object-Oriented Approach

Question

Which two method implementations are correct, when inserted independently in line 1? (Choose two.)

Options

  • Apublic boolean methodD(int x) { return x > 0; }
  • Bpublic String methodB() { System.out.println("methodB"); }
  • Cpublic char methodE (String msg) { return msg; }
  • Dpublic void methodC(int x) { return ++x; }
  • Epublic void methodA() { System.out.println("methodA"); }

How the community answered

(27 responses)
  • A
    81% (22)
  • B
    11% (3)
  • C
    4% (1)
  • D
    4% (1)

Explanation

Options A and E are correct because they both honor the contract between the declared return type and what the method actually returns. Option A declares boolean and returns x > 0, which is a valid boolean expression. Option E declares void and has no return statement - void methods simply execute and exit, so System.out.println(...) alone is perfectly valid.

Why the distractors fail:

  • B declares String as the return type but never returns a String - System.out.println() is a void call, leaving the compiler with an unfulfilled return promise.
  • C declares char but tries to return msg, where msg is a String - you cannot implicitly convert a String to a char.
  • D declares void but attempts return ++x, which is a value - void methods must not return any value at all.

Memory tip: Think of the return type as a promise - the method body must deliver exactly what was promised. void promises nothing (no return value allowed), any other type promises a value of that exact type. When you spot a mismatch between what's declared and what's returned (or returned when nothing should be), the method is broken.

Topics

#method signatures#return types#type matching#void methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice