Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java transient Keyword
Usage and Examples



transient Keyword in Java

In Java, the transient keyword is used in the context of serialization. If you're building a class that implements Serializable, you might not want all fields of that class to be saved when the object is written to a file or sent over a network. That’s exactly what transient is for — it tells the Java Virtual Machine (JVM) to skip a particular field during serialization.

What is Serialization?

Serialization is the process of converting an object into a byte stream so that it can be stored in a file or transmitted over a network. Deserialization is the reverse — converting that byte stream back into an object.

Why Use transient?

There are times when certain fields in a class are either:

In such cases, you can mark those fields as transient, and Java will ignore them during serialization.

Syntax

transient dataType variableName;

Basic Example of transient

import java.io.*;

class User implements Serializable {
    String username;
    transient String password; // This will not be serialized

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

public class TransientExample {
    public static void main(String[] args) throws Exception {
        User user = new User("john_doe", "mySecret");

        // Serialize the user
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"));
        oos.writeObject(user);
        oos.close();

        // Deserialize the user
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"));
        User deserializedUser = (User) ois.readObject();
        ois.close();

        System.out.println("Username: " + deserializedUser.username);
        System.out.println("Password: " + deserializedUser.password);
    }
}

Output

Username: john_doe
Password: null

Explanation

Here, the username field is serialized and preserved. However, the password field was marked as transient, so it was ignored during serialization. Upon deserialization, the password becomes null because its value wasn’t stored.

Real-World Use Case

Let’s say you're building a banking application. Your Account object contains a balance and a securityToken. The token is used only during active user sessions and should not be persisted. You can mark the token as transient.

class Account implements Serializable {
    String accountNumber;
    double balance;
    transient String securityToken; // Session-based, not to be persisted
}

Points to Remember

Advanced Tip: Custom Serialization Logic

private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject(); // serialize everything except transient
    // Add custom serialization logic here
}

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    ois.defaultReadObject(); // restore everything except transient
    // Add custom deserialization logic here
}

Summary

The transient keyword in Java gives you control over what gets serialized. It's used to protect sensitive information, exclude irrelevant data, and prevent serialization errors due to non-serializable members.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M