Java.Serialization.What does the transient keyword mean?

What does the transient keyword mean?

📘 Syntax

transient int secretCode;

🎯 Why Use transient?

Use CaseWhy transient Helps
Sensitive dataDon’t serialize passwords, tokens, keys
Large or cache-only fieldsDon’t waste space storing something you can rebuild
Non-serializable fieldsAvoid exceptions for things like threads, sockets, or DB connections
Temporary runtime dataTimestamp, session ID, logs, etc. that don’t need to persist

🔧 Example

import java.io.*;

public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    String username;
    transient String password; // excluded!

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

➕ Serialize:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"));
out.writeObject(new User("Stanley", "mySecret123"));
out.close();

➖ Deserialize:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"));
User u = (User) in.readObject();
System.out.println(u.username); // "Stanley"
System.out.println(u.password); // null (not serialized) ✅

⚠️ What Value Does a transient Field Have After Deserialization?

TypeValue
String, Objectnull
int, long0
booleanfalse

You can re-initialize them in:

  • A constructor
  • A custom readObject() method

🧵 TL;DR

FeatureMeaning
transientPrevents a field from being serialized
Used forSensitive, temporary, or non-serializable data
Value after deserializationDefault Java value (null, 0, false)
Applies toFields only (not classes or methods)
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.