Return to site

☕🎓JAVA CERTIFICATION QUESTION: serialization and var

· java

Given the following Person record:

record Person(String name) implements Serializable {}

and the following method fragment:

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename))) {
  ... // code here
  System.out.println(person.name());
}

Assume that the try block is completed with necessary catch blocks and the file contains a serialized Person and opens correctly.

The code from which option, when placed where the comment is, properly deserializes the object and allows the rest of the code to work?

Choose one.

* 'var & casting'

var person = (Person) null;
if (in.readObject() instanceof Person p) {
 person = p;
}

* 'var & no casting'

var person = in.readObject();

* 'no var & no casting'

Person person = null;
if (in.readObject() instanceof Person) {
 person = in.readObject();
}

* 'var and null'

var person = null;
Object o = in.readObject();
if (o instanceof Person) {
 person = (Person) o;
}

#java #certificationquestion #ocp

Answer: The right option is 'var & casting'

The other options are wrong:

'var & no casting' is wrong because the return type of the readObject method is declared as Object; so var will infer an Object type rather than a Person type.

Then calling the person.name() will fail (because Object has no name(0 method).

'no var & no casting' is wrong: first, because we call twice readObject(), so we miss the first.

Secondly, because person is a Person type and we assign an Object type.

We should cast it like: 'person = (Person)in.readObject();'.

'var and null' is wrong because var can't infer the type from null.