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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.