ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Map<String, Integer> m = new HashMap<>();
System.out.print(m.putIfAbsent("k", 1) + " ");
System.out.print(m.putIfAbsent("k", 2) + " ");
System.out.print(m.computeIfAbsent("k", s -> 3) + " ");
System.out.print(m.get("k"));- A. 1 2 3 3
- B. null 1 1 1
- C. null 1 3 3
- D. null null 1 1
Correct answer: B. null 1 1 1
putIfAbsent returns the PREVIOUS value (null, then 1) and does not overwrite. computeIfAbsent returns the current value (1) without calling the function because the key is present.
More OOP with C++ and Java questions
- 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…
- What is printed? java int[] a = {1, 2}, b = {1, 2}; int[][] p = {{1}}, q = {{1}}; System.out.print(a.equals(b) + " " + Arrays.equals(a, b)…