ProgrammingModerateProduct-company placement · Java
What is printed?
What is printed?
Map<Character, Integer> f = new TreeMap<>(); for (char c : "banana".toCharArray()) f.merge(c, 1, Integer::sum); System.out.print(f);
- A. {b=1, a=3, n=2}
- B. {a=3, b=1, n=2}
- C. {a=1, b=1, n=1}
- D. {a=3, n=2, b=1}
Correct answer: B. {a=3, b=1, n=2}
merge inserts 1 for a new key and otherwise combines old and new with Integer::sum, counting each letter. A TreeMap prints its keys in sorted order, not insertion order.
More OOP with C++ and Java questions
- 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 =…
- What is printed? java Object[] arr = new String[2]; arr[0] = "ok"; try { arr[1] = 42; System.out.print("stored"); } catch…