Customized serialization in Java

I have the following class

class UserAccount implements Serializable
    public String username;
    public String password;

    public UserAccount()
        username = "defaultUsername";
        password = "defaultPassword";

    public UserAccount(String u, String p)
        username = u;
        password = p;

    private void readObject(ObjectInputStream o) 
            throws IOException, ClassNotFoundException
        //username = (String)o.readObject();

    private void writeobject(ObjectOutputStream o) 
            throws IOException, ClassNotFoundException


    public String toString()
        return username + ", " + password;

And I wrote the following snippet to serialize and de-serialize an instance of it.

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("out.dat")));

out.writeObject(new UserAccount("test", "test2"));


ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("out.dat")));

UserAccount u = (UserAccount)in.readObject();



I am customizing the serialization using the writeObject() hook, such that, I am only persisting the username. But when I read back the object, I do the default de-serialization.

I am expecting the output to be test, null while the out put is test, test2

Basically I am expecting the member password to be null since I did not persist it. Can anyone help me understand how password is initialized to test2.

I also verified that the call to the constructor was not made[I knew it wouldn’t be made, but I checked nevertheless] during deserialization.

Thanks in advance.


Use the transient keyword to variables to make them not serialized. This might be another solution to skaffman’s answer.

Reference: Why does Java have transient fields?

Leave a Reply

Your email address will not be published. Required fields are marked *