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"));
}
}- A. 3 apple
- B. 7 banana
- C. Compile-time error: max cannot be called with both Integer and String
- 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
- What is printed? java class Box<T> { private T value; void set(T v) { value = v; } T get() { return value; } } public class Main { public…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 200…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java class Base { void show() { System.out.print("Base"); } } class Sub extends Base { void show() {…
- What is printed? cpp struct Animal { virtual std::string sound() const = 0; void makeSound() const { cout << sound(); } virtual ~Animal()…
- What is printed? java class Base { Base() { System.out.print("Base-ctor "); } static { System.out.print("Base-static "); } } class Sub…