ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
int x = m.getOrDefault("b", 0) + m.get("a");
int y = m.get("b");
System.out.print(x + y);- A. 1
- B. A NullPointerException is thrown; nothing is printed
- C. Compile-time error
- D. 1null
Correct answer: B. A NullPointerException is thrown; nothing is printed
x is 0 + 1 = 1, but m.get("b") returns null and assigning it to an int auto-unboxes null, which throws NullPointerException before the print.
More OOP with C++ and Java questions
- 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 =…
- Which lines fail to compile? java List<? super Integer> l = new ArrayList<Number>(); l.add(1); // L1 l.add(2.5); // L2 Object o =…