Return to site

☕🎓JAVA CERTIFICATION QUESTION: record deserialization

· java,ocp

Imagine you are given the following enum and record:

Previously an instance of Person was constructed like the following and serialized to a file:

var v = new Person(60, "John Doe", Gender.MALE);

What might be printed to the console when a program deserializes the contents of the file mentioned above? Choose two.

  • Gender PersonC Person
  • Gender PersonC
  • PersonC Person
  • PersonC
  • Gender Gender Gender Person PersonC
  • GenderS GenderS Gender Person PersonC
  • GenderS GenderS Gender PersonC

#java #certificationquestion #ocp

Answer:

This question investigates the mechanisms of deserialization for both enum types and records.

When a record is deserialized, each of the attributes—in this case, the age, name, and gender attributes—must be deserialized to their respective objects or values first.

These attributes are then passed to the canonical constructor of the record.

No output is printed in handling the int age and the String name attributes, but it’s possible that output might be printed for Gender.

For the Gender enum, there are now two distinct possibilities:

First: the enum has not been fully prepared.

In this situation, expect the three instances (MALE, FEMALE,OTHER) to be initialized using their appropriate constructors.

So, in this situation, you will see GenderS GenderS Gender as the output, preceding any output referring to Person.

Secondly: the Gender type has been fully prepared before the moment when an instance of Person is deserialized.

So, no messages related to Gender will be output by the deserialization process.

Once the enum is fully prepared, deserialization of the record type can proceed.

Note that for record: the (compact) canonical constructor for a record type is invoked to perform the initialization of the newly allocated object.

So, you will see the message PersonC printed as output.

Because you might or might not see GenderS GenderS Gender, and you will see PersonC in the output, the two valid answers are

PersonC

GenderS GenderS Gender PersonC