1Z0-811 Core Java API 2 — Questions and Answers
Question 1: What does `String.valueOf(null)` return when the argument is a `char[]` variable set to null?
- "null"
- null
- NullPointerException (Correct answer)
- Empty string
Correct answer: NullPointerException
Calling `String.valueOf((char[]) null)` throws a NullPointerException because the char[] overload dereferences the array.
Question 2: Which method of `StringBuilder` reverses the character sequence in place?
- flip()
- reverse() (Correct answer)
- invert()
- mirror()
Correct answer: reverse()
`StringBuilder.reverse()` reverses the sequence of characters and returns the same StringBuilder.
Question 3: Given `List<String> list = List.of("a","b","c");`, what happens when you call `list.set(0, "z")`?
- Returns the old value "a"
- Replaces "a" with "z"
- Throws UnsupportedOperationException (Correct answer)
- Throws IndexOutOfBoundsException
Correct answer: Throws UnsupportedOperationException
Lists created with `List.of()` are immutable, so any structural or element-change operation throws UnsupportedOperationException.
Question 4: What is the output of `System.out.println(Math.floor(-2.5))`?
- -2.0
- -3.0 (Correct answer)
- 2.0
- -2.5
Correct answer: -3.0
`Math.floor()` returns the largest double less than or equal to the argument, so -2.5 floors to -3.0.
Question 5: Which interface does `HashMap` directly implement?
- SortedMap
- LinkedMap
- Map (Correct answer)
- TreeMap
Correct answer: Map
`HashMap` directly implements the `Map` interface and extends `AbstractMap`.
Question 6: What is the result of `"hello".substring(2, 4)`?
- "ell"
- "ll" (Correct answer)
- "lo"
- "llo"
Correct answer: "ll"
`substring(beginIndex, endIndex)` returns characters from index 2 (inclusive) to 4 (exclusive): 'l' and 'l'.
Question 7: Which `Optional` method returns the value if present, otherwise throws `NoSuchElementException`?
- get() (Correct answer)
- orElse(null)
- orElseThrow()
- ifPresent()
Correct answer: get()
`Optional.get()` returns the value if present, but throws `NoSuchElementException` if the Optional is empty.
What does `String.valueOf(null)` return when the argument is a `char[]` variable set to null?