CKTIS / Java
transient — excluding a field from default serialization
The transient keyword excludes a field from Java's implicit list of serializable fields. If the field is omitted, it retains its default value after an ordinary Serializable object is read back, unless restoration code assigns another value.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
transient Type fieldName;transient is a reserved keyword and a field modifier, not a modifier for methods, parameters, or local variables. It indicates that a field is not part of an object's persistent state. The modifier alone does not make a class serializable; standard object serialization requires Serializable.
The implicit list of serializable fields includes instance fields that are neither static nor transient. A private field is not automatically omitted. Fields marked static belong to the class, so they do not need transient to exclude them from this list. A class can override the implicit list with a valid serialPersistentFields declaration. ObjectOutputStream uses the declared list for default state writing even if the class does not define a custom writeObject method.
When an ordinary Serializable class is deserialized, its constructor and instance field initializers are not executed. Without additional restoration code, an omitted field retains its type's default value, such as null, 0, or false. Thus, in the example, cache is null after reading, not "ready", while score retains 42. A cache can be rebuilt in readObject when needed.
transient does not encrypt data and is not a security boundary. A custom writeObject method can explicitly write the field's value, and Externalizable lets a class control writing and reading. Do not assume that other serialization mechanisms follow the same rules either. The example reads only bytes it created itself; deserializing untrusted data is dangerous.
Examples
import java.io.*;
public class TransientDemo {
private static class State implements Serializable {
private static final long serialVersionUID = 1L;
int score = 42;
transient String cache = "ready";
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
State original = new State();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(original);
}
State restored;
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()))) {
restored = (State) in.readObject();
}
System.out.println(original.score + " " + original.cache);
System.out.println(restored.score + " " + restored.cache);
}
}Result
42 ready 42 null
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.