ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    static <T extends Comparable<T>> T max(T a, T b) {
        return a.compareTo(b) >= 0 ? a : b;
    }
    public static void main(String[] args) {
        System.out.println(max(3, 7) + " " + max("apple", "banana"));
    }
}
  1. A. 3 apple
  2. B. 7 banana
  3. C. Compile-time error: max cannot be called with both Integer and String
  4. D. 7 apple

Correct answer: B. 7 banana

Both Integer and String implement Comparable<T> against themselves, so both calls satisfy the bound T extends Comparable<T>. max(3, 7) compares 3 and 7, returning 7; max("apple","banana") compares lexicographically, and "banana" > "apple", so it returns banana.

More OOP with C++ and Java questions

Exams that ask this topic