ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
Map<String, Integer> m = new HashMap<>();
System.out.print(m.put("a", 1));
System.out.print(m.put("a", 2));
System.out.print(m.putIfAbsent("a", 3));
System.out.print(m.get("a"));- A. null123
- B. null122
- C. 1223
- D. null1null2
Correct answer: B. null122
put returns the previous value: null the first time, then 1. putIfAbsent finds a present key, changes nothing and returns the current value 2, and get returns 2.
More OOP with C++ and Java questions
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.merge("k", 5, Integer::sum); m.merge("k", 5, Integer::sum); m.merge("k"…
- What is printed? java TreeMap<Integer, String> t = new TreeMap<>(); for (int k : new int[]{40, 10, 30, 20}) t.put(k, "v")…
- What is printed? java Deque<Integer> d = new ArrayDeque<>(); d.push(1); d.push(2); d.offer(3); d.addFirst(4); System.out.print(d.pop() +…
- What is printed? java Integer[] arr = {1, 2, 3}; List<Integer> l = Arrays.asList(arr); arr[0] = 7; l.set(2, 9); System.out.print(l + " " +…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4, 5)); l.subList(1, 3).clear(); System.out.print(l);
- What is printed? java System.out.print("a,b,,c,,".split(",").length + " " + ",a".split(",").length + " " + "a,b,,c,,".split(","…