ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
class Box<T> { static int count = 0; Box() { count++; } }
// in main:
new Box<String>(); new Box<Integer>(); new Box<String>();
System.out.print(Box.count);
  1. A. 2
  2. B. 3
  3. C. 1
  4. D. Compile-time error: static field in a generic class

Correct answer: B. 3

Generics are erased: Box<String> and Box<Integer> are the same runtime class Box, so there is one static count shared by all three objects.

More OOP with C++ and Java questions

Exams that ask this topic