ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class Repo<T> {
private List<T> items = new ArrayList<>();
void add(T item) { items.add(item); }
T get(int i) { return items.get(i); }
}
// in main:
Repo<Integer> repo = new Repo<>();
repo.add(10);
repo.add(20);
int sum = repo.get(0) + repo.get(1);
System.out.println(sum);- A. 30
- B. 1020
- C. Compilation error: cannot add int to the generic List<T>
- D. It throws a ClassCastException at run time
Correct answer: A. 30
At compile time T is bound to Integer, so autoboxing handles add(10)/add(20) and get() returns Integer which unboxes automatically for the + operator (an inserted synthetic cast to Integer after erasure makes this safe at run time too): 10 + 20 = 30.
More OOP with C++ and Java questions
- What is printed? java interface Shape { double area(); default String describe() { return "Shape with area " + area(); } } class Square…
- What is printed? cpp struct A { int x = 10; virtual int getX() { return x; } }; struct B : A { int x = 20; int getX() override { return x…
- What is printed? java class Util { static int counter = 0; static void inc() { counter++; } } class UtilChild extends Util { } public…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? java interface Shape { static double unit() { return 1.0; } double area(); } class Square implements Shape { double side…
- What is printed? cpp struct Counter { static int next() { static int n = 0; return ++n; } }; int main() { cout << Counter::next() <<…