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);
}
}- A. 15
- B. Compile-time error: cannot add int to T
- C. Compile-time error: box.get() returns Object, not Integer
- 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
- 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…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct Mid : Base { }; struct Leaf : Mid { void f() override {…