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);
  1. A. null 5
  2. B. fallback 5
  3. C. fallback null
  4. 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

Exams that ask this topic