ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Box<T> {
    private T value;
    void set(T v) { value = v; }
    T get() { return value; }
}
public class Main {
    public static void main(String[] args) {
        Box<Integer> box = new Box<>();
        box.set(5);
        int x = box.get() + 10;
        System.out.println(x);
    }
}
  1. A. 15
  2. B. Compile-time error: cannot add int to T
  3. C. Compile-time error: box.get() returns Object, not Integer
  4. D. 5

Correct answer: A. 15

Generics give compile-time type safety with erasure under the hood: box.get() is statically typed as Integer (the compiler inserts an implicit cast), which auto-unboxes to int for the addition, giving 5 + 10 = 15.

More OOP with C++ and Java questions

Exams that ask this topic