ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Container<T extends Comparable<T>> {
    T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; }
}
// in main:
Container<Integer> c = new Container<>();
System.out.println(c.max(3, 7));
  1. A. 3
  2. B. 7
  3. C. Compilation error: Integer does not implement Comparable<Integer>
  4. D. Compilation error: T extends Comparable<T> is invalid syntax

Correct answer: B. 7

Integer does implement Comparable<Integer>, satisfying the bound T extends Comparable<T>, so Container<Integer> is valid. max(3, 7) compares 3.compareTo(7), which is negative, so the method returns b (7).

More OOP with C++ and Java questions

Exams that ask this topic