nerdexam
Oracle

1Z0-811 · Question #16

Given public class App { int num; public int add(int x) { num = num + x; return num; } public void add(int x) { num = num + x; } public static void main (String[] args) { App obj = new App()…

The correct answer is D. A compilation error occurs. D is correct because Java does not allow method overloading based solely on return type - both add(int x) methods have identical parameter lists, so the compiler cannot distinguish between them and throws a compilation error before the program ever runs. The distractors (A, B…

Object-Oriented Programming Principles

Question

Given public class App { int num; public int add(int x) { num = num + x; return num; } public void add(int x) { num = num + x; } public static void main (String[] args) { App obj = new App(); obj.add (100); int ans = obj.add(100); System.out.println (obj.num); } } What is the result?

Options

  • A300
  • B100
  • C200
  • DA compilation error occurs.

How the community answered

(49 responses)
  • A
    10% (5)
  • B
    6% (3)
  • C
    4% (2)
  • D
    80% (39)

Explanation

D is correct because Java does not allow method overloading based solely on return type - both add(int x) methods have identical parameter lists, so the compiler cannot distinguish between them and throws a compilation error before the program ever runs.

The distractors (A, B, C) all assume the program executes, but since it never compiles, no output is produced: 200 would require both calls to succeed, 100 would suggest only one call ran, and 300 would imply some triple accumulation - none of which can happen.

Memory tip: Think of Java's method signature as a name tag that includes only the method name and parameter types (not the return type). Two methods with the same name tag are always illegal, regardless of what they return.

Topics

#Method Overloading#Method Signature#Return Type Rules#Compilation Error

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice