ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Map<String, Integer> h = new HashMap<>(); h.put(null, 1); h.put(null, 2); System.out.print(h.size() + " " + h.get(null) + " "); Map<String, Integer> t = new TreeMap<>(); t.put(null, 1); System.out.print(t.size());
- A. 1 2 1
- B. 2 2 1
- C. Compile-time error at t.put(null, 1)
- D. 1 2 is printed, then a NullPointerException is thrown
Correct answer: D. 1 2 is printed, then a NullPointerException is thrown
HashMap permits one null key, so the second put just replaces its value. A TreeMap with natural ordering must compare keys and throws NullPointerException for a null key; the code compiles fine.
More OOP with C++ and Java questions
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.put("a", 1); int x = m.getOrDefault("b", 0) + m.get("a"); int y =…
- What is printed? java Map<Character, Integer> f = new TreeMap<>(); for (char c : "banana".toCharArray()) f.merge(c, 1, Integer::sum)…
- What is printed? java Map<String, Integer> m = new HashMap<>(); System.out.print(m.putIfAbsent("k", 1) + " ")…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6)); l.subList(1, 4).clear(); System.out.print(l);
- What is printed? java List<String> a = Arrays.asList("x", null); System.out.print(a.size() + " "); List<String> b = List.of("x", null)…
- Which lines fail to compile? java List<Integer> ints = new ArrayList<>(); List<Number> nums = ints; // L1 List<? extends Number> ext =…