What is transient keyword in Java: Explanation and Example
transient keyword is used to mark a variable so that it is not saved when an object is serialized. This means the variable's value is ignored during the process of converting the object into a byte stream for storage or transfer.How It Works
Imagine you have a box with many items, and you want to send this box to a friend. Serialization in Java is like packing the box so it can be sent over a network or saved to a file. However, some items inside the box might be temporary or sensitive, and you don't want to include them in the package.
The transient keyword tells Java not to include certain variables when packing (serializing) the object. When your friend receives the box and unpacks it (deserializes), those transient variables will be empty or set to their default values because they were never packed.
This helps protect sensitive data or avoid saving unnecessary information that can be recalculated or is only relevant during runtime.
Example
This example shows a class with a transient variable. When the object is saved and loaded back, the transient variable does not keep its value.
import java.io.*; class User implements Serializable { String name; transient String password; // This will not be serialized User(String name, String password) { this.name = name; this.password = password; } } public class TransientExample { public static void main(String[] args) { User user = new User("Alice", "secret123"); try { // Serialize the user object to a file FileOutputStream fileOut = new FileOutputStream("user.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(user); out.close(); fileOut.close(); // Deserialize the user object from the file FileInputStream fileIn = new FileInputStream("user.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); User deserializedUser = (User) in.readObject(); in.close(); fileIn.close(); System.out.println("Name: " + deserializedUser.name); System.out.println("Password: " + deserializedUser.password); // Will print null } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
When to Use
Use the transient keyword when you want to exclude certain fields from being saved or sent during serialization. This is useful for:
- Protecting sensitive information like passwords or personal data.
- Skipping fields that can be recalculated or are temporary, such as cache or session data.
- Reducing the size of the serialized object by ignoring unnecessary data.
For example, in a user profile object, you might want to save the username but not the password when storing the object.
Key Points
- transient variables are ignored during serialization.
- They get default values (null, 0, false) after deserialization.
- Useful for sensitive or temporary data.
- Only applies to instance variables, not static variables.
- Helps control what data is saved or sent.