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));- A. 3
- B. 7
- C. Compilation error: Integer does not implement Comparable<Integer>
- 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
- What is printed? java class Node<T> { T data; static int count; { count++; } Node(T d) { data = d; } } // in main: new Node<Integer>(1)…
- What is printed? java class Base { protected void show() { System.out.println("Base.show"); } } class Derived extends Base { @Override…
- What is printed? java class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int…
- What is printed? java class Shape { void draw() { System.out.println("Shape.draw"); } } class Circle extends Shape { void draw() {…
- Does this compile? java class Base { void greet() { System.out.println("Base.greet"); } } class Derived extends Base { @Override void…
- What is printed? java class Repo<T> { private List<T> items = new ArrayList<>(); void add(T item) { items.add(item); } T get(int i) {…