ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
m.keySet().remove("a");
System.out.print(m.size() + " ");
m.keySet().add("b");- A. "0 " is printed, then UnsupportedOperationException is thrown
- B. "0 " is printed, then b is added with value null
- C. 1 then UnsupportedOperationException
- D. Compile-time error: keySet() is read-only
Correct answer: A. "0 " is printed, then UnsupportedOperationException is thrown
keySet() is a live view: removing through it removes the mapping. Adding through it is unsupported, since a key alone does not say what value to store.
More OOP with C++ and Java questions
- What is printed? java TreeSet<Integer> s = new TreeSet<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); SortedSet<Integer> sub = s.subSet(3, 6)…
- What is printed? java List<String> l = Arrays.asList("b", null, "a"); l.sort(Comparator.nullsFirst(Comparator.naturalOrder()))…
- What is printed? java // static method of the main class: static String make() { System.out.print("M"); return "y"; } // in main…
- What is printed? java Stream<Integer> s = Stream.of(1, 2, 3); System.out.print(s.count()); System.out.print(s.count());
- What happens when this method is compiled (Java 7 or later)? java static void f() throws java.io.IOException { try { if (Math.random() <…
- What is printed? java try { System.out.print("T"); System.exit(0); } finally { System.out.print("F"); }