ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Util {
static <T> T firstNonNull(T a, T b) {
return a != null ? a : b;
}
}
// in main:
String s = Util.firstNonNull(null, "fallback");
Integer n = Util.firstNonNull(null, 5);
System.out.println(s + " " + n);- A. null 5
- B. fallback 5
- C. fallback null
- D. Compilation error: T cannot be inferred
Correct answer: B. fallback 5
Generic method type inference picks T = String for the first call and T = Integer for the second, purely from the compile-time argument/return context; at run time (after erasure, T is just Object) the logic simply returns the non-null argument, giving "fallback" and 5.
More OOP with C++ and Java questions
- What is printed? java class Container<T extends Comparable<T>> { T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } } // in main…
- 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…