ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Calculator {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}
// in main:
Calculator calc = new Calculator();
System.out.println(calc.add(1, 2) + " " + calc.add(1.0, 2) + " " + calc.add(1, 2, 3));
  1. A. 3 3.0 6
  2. B. 3 3 6
  3. C. Compilation error: ambiguous overload add(1.0, 2)
  4. D. 3.0 3.0 6

Correct answer: A. 3 3.0 6

These are all distinct overloads by parameter count/type (not overriding, since there's no inheritance involved): add(1,2) matches add(int,int) exactly (3); add(1.0, 2) requires widening 2 to double, uniquely matching add(double,double) (3.0); add(1,2,3) matches the three-arg overload (6).

More OOP with C++ and Java questions

Exams that ask this topic