Skip to lesson

transient fields

A transient field is a field that serialization skips. Its value is not written to the bytes, so after reading it starts empty: 0, false or null.

transient: skipping passwords and caches

A transient field is skipped during serialization, so its value is not saved; it gets its default value when the object is read back.

The keyword transient on a field tells serialization "do not save this one": transient String password;. The other fields are saved as usual.

A table for a PortalUser with three fields. username "sneha.k" is saved and read back as "sneha.k". password "Sneha@2005" is transient, so it is skipped and read back as null. loginCount 14 is saved and read back as 14.

Example 1 · A transient password never reaches the file

TransientPasswordDemo.javaJava
import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
class PortalUser implements Serializable {    String username;    transient String password;     // never written to the file    int loginCount;
    PortalUser(String username, String password, int loginCount) {        this.username = username;        this.password = password;        this.loginCount = loginCount;    }}
public class TransientPasswordDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        Path file = Path.of("user.ser");        PortalUser u = new PortalUser("sneha.k", "Sneha@2005", 14);
        try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(file))) {            out.writeObject(u);        }        String raw = new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1);        System.out.println("Password text in file? " + raw.contains("Sneha@2005"));        System.out.println("Username text in file? " + raw.contains("sneha.k"));
        try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(file))) {            PortalUser back = (PortalUser) in.readObject();            System.out.println(back.username + ", password=" + back.password + ", logins=" + back.loginCount);        }        Files.delete(file);    }}
Output
Password text in file? false
Username text in file? true
sneha.k, password=null, logins=14

What this code does

  • password is transient, so its text is not in the saved bytes; the username is.
  • After reading, password is null. The user must type it again, which is exactly what a login screen should ask for.
  • Looking for the text inside the bytes is only a quick check for this demo; it is not how you test real security.

Use it for three kinds of fields. Secrets such as passwords, PINs and OTPs, which must never sit in a file. Values you can work out again, such as a total or a lookup map, called a cache. And helper objects that cannot be serialized at all, such as a formatter or an open connection. The third kind also fixes NotSerializableException: a transient field is never written, so its class does not need to be Serializable.

Skipping a password with transient keeps it out of the file. It does not encrypt anything else in the file, and the other fields are still easy to read for anyone who has the bytes.

Default values after reading back

After deserialization, a transient field holds the default value of its type: 0 for numbers, false for boolean, '\u0000' for char and null for any object, including String and List.

Example 2 · Initializers do not run when reading

TransientDefaultsDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
class Post implements Serializable {    String title;    transient int views = 10;                          // initializer    transient boolean trending = true;                 // initializer    transient List<String> recentLikes = new ArrayList<>();
    Post(String title) {        this.title = title;        System.out.println("  constructor runs for " + title);    }}
public class TransientDefaultsDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        System.out.println("Creating:");        Post p = new Post("Fest photos");        p.views = 250;        p.recentLikes.add("Asha");
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(p);        }
        System.out.println("Reading:");        Post back;        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            back = (Post) in.readObject();        }        System.out.println("title=" + back.title);        System.out.println("views=" + back.views + ", trending=" + back.trending                + ", recentLikes=" + back.recentLikes);
        try {            back.recentLikes.add("Ben");        } catch (NullPointerException e) {            System.out.println("NullPointerException: recentLikes is null");        }    }}
Output
Creating:
  constructor runs for Fest photos
Reading:
title=Fest photos
views=0, trending=false, recentLikes=null
NullPointerException: recentLikes is null

What this code does

  • The constructor and the initializers = 10, = true and = new ArrayList<>() run when the object is created, but not when it is read back.
  • So the transient fields come back as 0, false and null, not as the values in the field declarations.
  • Calling add on the null list throws NullPointerException: the classic bug after adding transient to a collection.

This surprises many learners: field initializers and the constructor do not run for a serializable class when it is read. So transient int views = 10; comes back as 0, not 10, and transient List<String> likes = new ArrayList<>(); comes back as null. Code that uses such a field after loading must expect this, or the program crashes with NullPointerException the first time it calls a method on the field.

Predict the output

What comes back after reading?

Read each program and pick what it prints.

Round 1 of 3

A transient number in a shopping cart.

import java.io.*;
class Cart implements Serializable {
String owner = "Asha";
transient int items = 3;
}
public class CartDemo {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(new Cart());
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
Cart back = (Cart) in.readObject();
System.out.println(back.owner + " " + back.items);
}
}
}

static fields are not saved

A static field belongs to the class, not to one object, so serialization never saves it. Only the fields of the object itself (instance fields) are written.

Example 3 · A static field shows the reading program's value

StaticNotSavedDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class ExamEntry implements Serializable {    static String examName = "Mid-sem";    // belongs to the class, not to an object    String student;    int marks;
    ExamEntry(String student, int marks) {        this.student = student;        this.marks = marks;    }}
public class StaticNotSavedDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        ExamEntry e = new ExamEntry("Gopal", 67);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(e);                // written while examName is "Mid-sem"        }
        ExamEntry.examName = "End-sem";        // changed after saving
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            ExamEntry back = (ExamEntry) in.readObject();            System.out.println(back.student + " " + back.marks + " in " + ExamEntry.examName);        }    }}
Output
Gopal 67 in End-sem

What this code does

  • examName is static, so it is not part of the saved ExamEntry. Only student and marks are written.
  • The program changes examName after saving. The loaded entry shows "End-sem", the value the class has now.

After reading, a static field simply shows whatever value the class has in the program that is reading. If you saved an object while examName was "Mid-sem" and the reading program has "End-sem", you see "End-sem". So writing transient on a static field changes nothing. To save a counter or a setting, put it in an instance field of an object you save, or store it somewhere else.

Rebuilding transient values

A transient value often has to come back after loading. The first way is a private readObject method: Java calls it while reading the object; you call in.defaultReadObject() to read the normal fields, then rebuild the transient ones.

Example 4 · readObject rebuilds the total and the formatter

RebuildTotalDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.time.format.DateTimeFormatter;
class ReportCard implements Serializable {    String student;    int[] marks;    transient int total;                   // can be worked out from marks    transient DateTimeFormatter printFormat; // DateTimeFormatter is not Serializable
    ReportCard(String student, int[] marks) {        this.student = student;        this.marks = marks;        rebuild();    }
    private void rebuild() {        total = 0;        for (int m : marks) {            total += m;        }        printFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");    }
    // Called by Java while reading this object    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {        in.defaultReadObject();        rebuild();    }}
public class RebuildTotalDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        ReportCard card = new ReportCard("Harini", new int[] {82, 74, 91});
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(card);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            ReportCard back = (ReportCard) in.readObject();            System.out.println(back.student + ": total " + back.total);            System.out.println("Formatter ready? " + (back.printFormat != null));        }    }}
Output
Harini: total 247
Formatter ready? true

What this code does

  • total can be worked out from marks, and DateTimeFormatter is not serializable, so both fields are transient.
  • Java calls the private readObject while reading. in.defaultReadObject() reads student and marks, then rebuild() fills the transient fields again.
  • The same rebuild method is used by the constructor, so new and loaded objects are set up the same way.

Example 5 · Lazy rebuild: build the value on first use

LazyRebuildDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
class Playlist implements Serializable {    String name;    List<String> songs = new ArrayList<>();    private transient String summary;      // built on first use
    Playlist(String name) {        this.name = name;    }
    void add(String song) {        songs.add(song);        summary = null;                     // old summary is now out of date    }
    String summary() {        if (summary == null) {            System.out.println("  (building summary)");            summary = name + ": " + songs.size() + " songs, first is " + songs.get(0);        }        return summary;    }}
public class LazyRebuildDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        Playlist p = new Playlist("Road trip");        p.add("Ilahi");        p.add("Kun Faya Kun");        System.out.println("Before saving:");        System.out.println(p.summary());
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(p);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            Playlist back = (Playlist) in.readObject();            System.out.println("After reading:");            System.out.println(back.summary());            System.out.println(back.summary());        }    }}
Output
Before saving:
  (building summary)
Road trip: 2 songs, first is Ilahi
After reading:
  (building summary)
Road trip: 2 songs, first is Ilahi
Road trip: 2 songs, first is Ilahi

What this code does

  • The summary is built only when summary() is called and the field is null. After reading it is null, so the first call builds it again.
  • The second call after reading uses the stored value, so "(building summary)" prints once.
  • add sets the summary back to null because a new song makes the old summary wrong.

The method must be written exactly as private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException. With a different name, return type or parameter, Java silently ignores it and your fields stay empty.

The second common way is lazy rebuilding: a getter checks whether the transient field is null and builds it on first use. It needs no special method and also works for objects made with the constructor. The Records and validation lesson later uses readObject for checks too.

Next step

Check your understanding

12 quick questions