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"));
}
}- A. 3 apple
- B. 7 banana
- C. 7 apple
- 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
- Which statement is correct about this class? java public class Base { public void show() { } } class Sub extends Base { private void…
- Which statement is correct? java class Base { protected void configure() { } } class Derived extends Base { public void configure() { } }
- Which statement is correct? java final class Immutable { void f() { } } class Sub extends Immutable { }
- Which statement is correct? java class Base { final void process() { System.out.print("Base.process"); } } class Sub extends Base { void…
- What is printed? java class Outer { private int secret = 42; class Inner { int reveal() { return secret; } } } public class Main { public…
- Which statement about overload resolution with varargs is correct? java class A { void f(int a, int b) { System.out.print("fixed"); } void…