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);- A. 2
- B. 3
- C. 1
- 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
- Which lines fail to compile? java class G<T> { T[] arr = new T[10]; // L1 T make() { return new T(); } // L2 boolean is(Object o) { return…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); Iterator<Integer> it = l.iterator(); it.next(); it.remove()…
- What is printed? java Map<String, Integer> m = new LinkedHashMap<>(16, 0.75f, true); m.put("a", 1); m.put("b", 2); m.put("c", 3)…
- What is printed? java Map<String, Integer> m = new LinkedHashMap<>(); m.put("x", 1); m.put("y", 2); m.put("x", 3); System.out.print(m);
- What is printed? java TreeSet<Integer> s = new TreeSet<>(List.of(5, 1, 9, 3, 7)); System.out.print(s.headSet(5) + " " + s.tailSet(5) + " "…
- What is printed? java Set<List<Integer>> a = new HashSet<>(); a.add(List.of(1, 2)); a.add(new ArrayList<>(List.of(1, 2))); Set<int[]> b =…