Java Transient Keyword


In Java the transient keyword indicates to the serialization mechanism to leave a specific variable out of the serialization process.

Syntax

 transient dataType variableName;

notepad

Transient fields are not included in the byte stream when an object gets serialized.


Why Use transient?

  • Transient should be used to prevent sensitive data such as passwords and PINs from being stored.
  • The transient keyword allows developers to bypass serializing temporary or computed values.
  • You can decrease the size of a serialized object by using transient

Example

import java.io.*;

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

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

Example

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

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

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

        System.out.println("Username: " + u.username);
        System.out.println("Password: " + u.password); // null
    }
}
 

output

Username: john_doe
Password: null

notepad

The password was not serialized, so it's null after deserialization.




OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.