Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What does transient do? After deserialization, what values do transient fields have, and how do you restore them?

The transient keyword tells Java serialization to skip a field: its value is not written to the stream. After deserialization a transient field holds its type's default value, null, 0 or false, because Java does not run the constructors or field initialisers of a serializable class when it rebuilds the object. We restore such fields ourselves, either in a private readObject method or lazily the first time they are used.

Why this question is asked

transient looks like a small keyword, but it decides what survives when an object is saved to disk, put in a session, or sent to another JVM. Getting it wrong gives us the classic bug where an object works perfectly until it is deserialized, and then throws NullPointerException on a field that is clearly initialised in the source code. Interviewers ask about it to check that we know how deserialization really builds an object. In this answer, we will recap what default serialization writes, see transient in action, understand why the initialisers do not run, and then look at how to restore the fields, which fields deserve the keyword, and the one combination to avoid.

1A Quick Recap of Default Serialization

Serialization turns an object into bytes so we can store it or send it, and deserialization turns the bytes back into an object. When a class implements Serializable and does nothing else, Java uses default serialization: ObjectOutputStream writes the value of every non-static field, and follows references to write the objects those fields point to as well.

Static fields are never written, because they belong to the class, not to the object. transient is how we exclude an instance field too. We mark a field transient when its value should not, or cannot, travel with the object.

2Seeing transient Fields After a Round Trip

Here is a small class with one normal field and three transient ones, each with an initialiser. We serialize it to a byte array and read it back.

Java
class Report implements Serializable {
private String title = "Q3";
private transient int cachedLength = 42;
private transient List<String> lines = new ArrayList<>();
private transient boolean dirty = true;
}
Report copy = roundTrip(new Report()); // writes to bytes, reads back with ObjectInputStream
copy.title // "Q3": written and read back
copy.cachedLength // 0, not 42
copy.lines // null, not an empty list
copy.dirty // false, not true

Notice that the transient fields did not get their initial values back. They hold the defaults that the JVM puts into every freshly allocated object: 0 for numbers, false for booleans and null for references. Any code that later calls copy.lines.add(...) throws NullPointerException.

3Why the Initialisers Do Not Run

In Java, a field initialiser such as = new ArrayList<>() is not magic; the compiler copies it into every constructor of the class. So the question is really whether a constructor runs during deserialization, and for a serializable class the answer is no.

ObjectInputStream allocates the object without calling its constructor. It then walks up the class hierarchy to the first superclass that is not serializable, often Object, and runs only that class's no-argument constructor. After that it fills in the non-transient fields from the stream, setting even final fields directly. The constructors of Report and of any serializable parent never run, so neither do their field initialisers.

Step throughHow ObjectInputStream rebuilds a Report
  1. Read class descriptorname, serialVersionUID, field list
  2. Allocate the objectall fields hold defaults: null, 0, false
  3. Run Object's no-arg constructorfirst non-serializable superclass only
  4. Fill non-transient fieldstitle = "Q3" from the stream
  5. Has a private readObject?
    YesRun it: our chance to restore transient fieldsNoDone: transient fields stay at defaults

5 steps in order. Play them, or step through them one at a time.

Report's own constructor and initialisers never run.

This is deliberate. Serialization wants to recreate the object's saved state exactly, and running a constructor could change that state or have side effects. The cost is that anything the constructor would normally set up, including transient fields, is our job.

4Restoring transient Fields

The usual way to restore them is a private readObject method. Java looks for it by name and signature, calls it instead of its default reading, and we first call defaultReadObject() to read the normal fields, then rebuild the rest.

Java
class Report implements Serializable {
private String title = "Q3";
private transient List<String> lines = new ArrayList<>();
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // title = "Q3"
lines = new ArrayList<>(); // restored: an empty list again
}
}

The other way is lazy restoration: leave the field null and build it the first time a method needs it. This suits expensive values such as a parsed template or a computed hash, because we only pay for them if someone asks.

5Lazy Restoration and Its Catch

A lazy getter checks for the default value and computes the field when it finds it.

Java
private transient Pattern compiled; // a compiled regular expression, cheap to rebuild
Pattern compiled() {
if (compiled == null) compiled = Pattern.compile(regex);
return compiled;
}
private transient int cachedLength; // 0 after deserialization
int length() {
if (cachedLength == 0) cachedLength = computeLength(); // careful: 0 may also be a real value
return cachedLength;
}

But there is a catch: for a primitive, the default can also be a legitimate value. If the real length is 0, the check above recomputes it every time. For primitives it is cleaner to use a separate boolean flag, or a boxed Integer that is null until computed. And if several threads may call the getter at once, the lazy code needs the same care as any other lazy initialisation.

6Which Fields Should Be transient

transient fits three kinds of fields. The first is caches and derived values, which can be rebuilt from the real data, such as a hash code or a parsed form of a string. The second is resources tied to this JVM, such as a database connection, a socket, a thread or a lock; their state means nothing in another process, and many of them are not serializable at all. The third is data that must not leave the process, such as a password or a token held briefly in memory.

One combination to avoid is transient final. A final field can only be assigned in a constructor or initialiser, and neither runs during deserialization, so the field stays null and readObject cannot assign it because the compiler rejects the assignment. The only ways around it are reflection or replacing the object in readResolve, so in practice we drop final from transient fields that need restoring.

Good candidates for transient
Kind of fieldExampleHow to restore
Cache or derived valuecached hash, parsed templatelazily on first use
Local resourceConnection, Socket, ReentrantLockreadObject, or reacquire on use
Sensitive dataa password char[] held brieflydo not restore; ask again
Large rebuildable dataan index built from other fieldsreadObject or lazily

7Follow-up questions

Are static fields serialized?

No. Static fields belong to the class, not to any object, so they are never written. After deserialization the object sees whatever value the static field has in the receiving JVM, which may be different from the sender's. transient on a static field has no effect.

Does transient affect JSON libraries such as Jackson?

transient is a rule of Java serialization, and JSON libraries apply their own rules. Jackson, for example, works mainly through getters and setters, so a transient field with a public getter may still appear in JSON depending on its settings. If a field must not appear in JSON, use the library's own annotation, such as @JsonIgnore, and check your version's defaults.

What if a field's type is not serializable?

Default serialization throws NotSerializableException when it reaches it. Marking the field transient is the usual fix when the value can be rebuilt; otherwise we write a serializable representation in writeObject and rebuild the object in readObject.

8Conclusion

In this answer, we saw that transient fields are skipped by default serialization and come back holding null, 0 or false, because deserialization allocates the object without running the constructors or field initialisers of serializable classes. We restore them in a private readObject after defaultReadObject, or lazily on first use with care for primitive defaults. We use transient for caches, derived values, local resources such as connections and locks, and sensitive data, and we avoid transient final, which cannot be reassigned without reflection.

What to say in the interviewAbout 80 seconds aloud

Open with

transient marks a field that default Java serialization should skip, so its value is never written to the stream. When the object is deserialized, that field holds the default value for its type: null for references, 0 for numbers and false for booleans.

Then, if they want more

That surprises people, because the field often has an initialiser in the code, but initialisers are really part of the constructor, and ObjectInputStream does not run the constructors of serializable classes. It allocates the object, runs only the no-argument constructor of the first non-serializable superclass, usually Object, and then fills in the non-transient fields from the stream.

So restoring transient fields is our job. The common way is a private readObject method that calls defaultReadObject first and then rebuilds the field, for example creating a new lock or an empty cache.

The other way is lazily, building the value the first time a getter needs it, with a flag or a boxed type if zero could be a real value. I use transient for caches and derived values, for resources like connections, sockets and locks that mean nothing in another JVM, and for sensitive data.

And I avoid transient final, because readObject cannot assign a final field without reflection, so the field would stay null.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does transient do? After deserialization, what values do transient fields have, and...": https://scrivio-interview-library.netlify.app/java/serialization/d96f02a12c/