ProgrammingHardAccenture · Cognizant 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.print(max(3, 7) + " " + max("apple", "banana"));
    }
}
  1. A. 3 apple
  2. B. 7 banana
  3. C. 7 apple
  4. D. Compilation error: T must be a concrete type

Correct answer: B. 7 banana

Integer and String both implement Comparable<T> with themselves as the type argument, satisfying the bound `T extends Comparable<T>`. compareTo determines ordering: 7 >= 3 so max(3,7)=7; "banana".compareTo("apple") is positive (b>a lexicographically) ... actually compareTo is called on a against b: 3.compareTo(7)<0 picks b=7; "apple".compareTo("banana")<0 picks b="banana". Result: 7 banana.

More OOP with C++ and Java questions

Exams that ask this topic