What is the difference between writeObject() and readObject() methods in Java serialization?

writeObject() and readObject() are special methods used to customize the serialization and deserialization process in Java. They allow developers to control how object data is written to and restored from a byte stream, making them useful for handling complex serialization requirements.

Key Points: • writeObject() is executed during serialization to control how object data is written. • readObject() is executed during deserialization to control how object data is restored. • These methods are commonly used to serialize transient fields, encrypt sensitive data, or perform validation. • Both methods work with ObjectOutputStream and ObjectInputStream. • They provide fine-grained control over the default serialization mechanism.

Example: Suppose a User class contains a transient password field. Normally, transient fields are not serialized. Using writeObject() and readObject(), the password can be manually serialized and restored if required.

Code Example:

import java.io.*;

class User implements Serializable {

    private String username;

    private transient String password;

    private void writeObject(ObjectOutputStream out)
            throws IOException {

        out.defaultWriteObject();

        out.writeObject(password);
    }

    private void readObject(ObjectInputStream in)
            throws IOException, ClassNotFoundException {

        in.defaultReadObject();

        password = (String) in.readObject();
    }
}

In this example:

• defaultWriteObject() serializes normal fields. • writeObject() manually writes the transient password. • defaultReadObject() restores normal fields. • readObject() manually restores the password.

Difference Between writeObject() and readObject():

writeObject(): • Used during serialization • Writes object data to the stream • Works with ObjectOutputStream • Customizes how data is stored

readObject(): • Used during deserialization • Reads object data from the stream • Works with ObjectInputStream • Customizes how data is restored

Common Use Cases:

• Serializing transient fields • Encrypting sensitive information • Data validation during deserialization • Backward compatibility handling • Custom object state management

Interview Tip: A concise interview answer is:

"writeObject() and readObject() are special methods used to customize Java serialization. writeObject() controls how an object is written to a stream during serialization, while readObject() controls how it is reconstructed during deserialization. They are commonly used for handling transient fields, validation, encryption, and custom serialization logic."