Return to site

☕🎓JAVA CERTIFICATION QUESTION: serialization and var

· java,ocp

Given the following Person record:

and the following method fragment:

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 & no casting'

* 'no var & no casting'

* 'var and null'

#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 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.