1Z0-811 Core Java API 3 — Questions and Answers
Question 1: What does `Collections.unmodifiableList(list)` guarantee?
- The backing list cannot be changed either
- Mutations through the wrapper throw UnsupportedOperationException (Correct answer)
- The list is sorted on access
- Elements are copied into a new immutable list
Correct answer: Mutations through the wrapper throw UnsupportedOperationException
The unmodifiable wrapper throws UnsupportedOperationException on mutating calls, but mutations to the backing list are still visible through the wrapper.
Question 2: What is printed by `System.out.println(Integer.toBinaryString(-1))`?
- "-1"
- "11111111111111111111111111111111" (Correct answer)
- "10000001"
- "0"
Correct answer: "11111111111111111111111111111111"
`Integer.toBinaryString(-1)` returns the unsigned 32-bit binary representation of -1, which is 32 ones.
Question 3: Which `Map` method returns the value associated with a key, or a default if the key is absent?
- computeIfAbsent()
- getOrDefault() (Correct answer)
- putIfAbsent()
- merge()
Correct answer: getOrDefault()
`Map.getOrDefault(key, defaultValue)` returns the mapped value or the specified default without modifying the map.
Question 4: What is the result of `String.format("%05d", 42)`?
- "42000"
- "00042" (Correct answer)
- " 0042"
- "42 "
Correct answer: "00042"
The format specifier `%05d` pads the integer with leading zeros to a width of 5, producing "00042".
Question 5: Which statement about `ArrayList` vs `LinkedList` is accurate?
- LinkedList has O(1) random access
- ArrayList has O(1) add at middle
- ArrayList has O(1) random get by index (Correct answer)
- LinkedList uses less memory per element
Correct answer: ArrayList has O(1) random get by index
ArrayList backed by an array supports O(1) index-based access, while LinkedList requires O(n) traversal to reach an element.
Question 6: What does `Math.round(2.5)` return in Java?
- 2
- 3 (Correct answer)
- 2.5
- 3.0
Correct answer: 3
`Math.round(2.5)` returns 3 (a long); it uses half-up rounding, so .5 always rounds toward positive infinity.
Question 7: What exception is thrown when you access an index beyond the end of an array?
- IndexOutOfBoundsException
- ArrayIndexOutOfBoundsException (Correct answer)
- NullPointerException
- IllegalArgumentException
Correct answer: ArrayIndexOutOfBoundsException
Accessing an invalid array index throws `ArrayIndexOutOfBoundsException`, a subclass of IndexOutOfBoundsException.
What does `Collections.unmodifiableList(list)` guarantee?