Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 16
Question ID: UKOCP86428
Given code:
- package com.udayankhattry.ocp;
- import java.io.*;
- import java.util.List;
- import java.util.Optional;
- public class Test {
- public static void main(String[] args) throws IOException, ClassNotFoundException {
- var optional = Optional.of(List.of("O", "N"));
- try (var oos = new ObjectOutputStream(new FileOutputStream(("F:\\data.ser")));
- var ois = new ObjectInputStream(new FileInputStream("F:\\data.ser")))
- {
- oos.writeObject(optional);
- var object = (Optional<?>)ois.readObject();
- System.out.println(object.get());
- }
- }
- }
F: is accessible for reading/writing and currently doesn't contain any files/directories.
What is the result?
- A Compilation error
- B Runtime Exception
- C [O, N]
- D [N, O]
Reveal correct answer
Correct answer: B
Explanation
UKOCP86428:
Variable 'optional' infers to Optional<List<String>> type, variable 'oos' infers to ObjectOutputStream type, variable 'ois' infers to ObjectInputStream type and variable 'object' infers to Optional<?> type.
There is no compilation error in this code.
Optional class doesn't implement Serializable interface, hence oos.writeObject(optional); throws NotSerializableException at runtime.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
