nerdexam
Oracle

1Z0-819 · Question #84

Given: public class SerializedMessage implements Serializable { String message; LocalDateTime createdTime; transient LocalDateTime updatedDateTime; SerializedMessage(String message) { this.message =…

The correct answer is B. After this object is deserialized. Option B is correct because Java's serialization framework automatically invokes readObject via reflection when reconstructing (deserializing) an object from a byte stream - specifically, after in.defaultReadObject() has restored the non-transient fields (message and…

Java I/O API

Question

Given: public class SerializedMessage implements Serializable { String message; LocalDateTime createdTime; transient LocalDateTime updatedDateTime; SerializedMessage(String message) { this.message = message; this.createdTime = LocalDateTime.now(); } private void readObject (ObjectInputStream in) { try { in.defaultReadObject(); this.updatedDateTime = LocalDateTime.now(); } catch (IOException |ClassNotFoundException e) { e.printStackTrace(); } } } When is the readObject method called?

Options

  • ABefore this object is deserialized
  • BAfter this object is deserialized
  • CBefore this object is serialized
  • DThe method is never called

How the community answered

(43 responses)
  • A
    14% (6)
  • B
    77% (33)
  • C
    7% (3)
  • D
    2% (1)

Explanation

Option B is correct because Java's serialization framework automatically invokes readObject via reflection when reconstructing (deserializing) an object from a byte stream - specifically, after in.defaultReadObject() has restored the non-transient fields (message and createdTime). The custom code that follows then initializes updatedDateTime, which was excluded from serialization due to the transient keyword.

A is wrong because readObject is not a pre-deserialization hook; it is the deserialization handler - it runs as the mechanism for restoring the object, not before it begins.

C is wrong because readObject has no role in serialization at all; its counterpart is writeObject, which is called during the write/serialize phase.

D is wrong because Java calls readObject automatically via reflection when it detects the method exists on a Serializable class - no explicit call is needed.

Memory tip: Match the method name to the direction of data flow - readObject reads data in (deserialization), writeObject writes data out (serialization). "After deserialized" is correct because defaultReadObject() must run first to restore the object's state before your custom logic can build on it.

Topics

#Serialization#readObject#Deserialization#ObjectInputStream

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice