View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Transient Keyword in Java: What is it & How it Works?

By Pavan Vadapalli

Updated on May 28, 2025 | 20 min read | 10.76K+ views

Share:

Did you know? Java remains one of the top programming languages in 2025. It ranked #2 in Pluralsight’s annual report and held the #3 spot in both the TIOBE Index (November 2024) and RedMonk Q3 2024 rankings, just behind Python and C++ or JavaScript. Its consistent performance shows Java’s lasting importance in today’s tech ecosystem. This study showcases the importance of Java in the tech industry. 

The transient keyword in Java controls object serialization, a process widely used in network communication, caching, and data persistence. By marking a variable as transient, you are telling the Java Virtual Machine (JVM) to skip that field when saving the object’s state to a stream.

Understanding how the transient keyword works helps you design secure, efficient, customizable data transfer processes. It is handy when dealing with sensitive information like passwords or session tokens that should not be persisted or exposed.

This blog explores the transient keyword in Java, how it functions during serialization, and when to use transient in Java applications. 

Looking to deepen your Java expertise? upGrad’s Online Software Development Courses cover core concepts like object serialization, the transient keyword, and more, equipping you with the skills needed to write secure, efficient Java applications. Enroll now to take your Java programming to the next level!

What Is the Transient Keyword in Java with Example?

The transient keyword in Java indicates that a particular class field should not be serialized. Serialization is converting an object’s state into a byte stream, and by marking a variable as transient, you tell the Java Virtual Machine (JVM) to skip it during this process.

This is especially useful when working with sensitive information, such as passwords or session tokens, that should not be stored or shared.

Syntax:


class ClassName implements Serializable {
    private transient dataType variableName;
}

Syntax Breakdown:

  • transient: Keyword that marks a variable as non-serializable.
  • dataType: The type of data the variable holds (e.g., int, String, boolean).
  • variableName: The name of the variable you want to mark as transient.

If you aim to strengthen your understanding of Java and related programming concepts, these additional courses from upGrad can help you advance. 

Transient keyword example Java


import java.io.*;

class User implements Serializable {
    private String username;
    private transient String password; // marked transient, won't be serialized

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

    @Override
    public String toString() {
        return "User{username='" + username + "', password='" + password + "'}";
    }
}

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

        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();

            System.out.println("Serialized user: " + user);

            // 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("Deserialized user: " + deserializedUser);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Explanation:

  • transient String password: The password field will not be serialized. It will be skipped during the process of saving the object’s state.
  • String username: This field will be included in the serialized data.
  • class User implements Serializable: The class must implement the Serializable interface for serialization to work.

Output:

Serialized user: User{username='john_doe', password='mySecret123'}
Deserialized user: User{username='john_doe', password='null'}

Output Explanation:

  • The username is saved when you serialize the user object because it’s a regular field.
  • The password field is marked as transient, so it is not saved during serialization.
  • After deserialization, the username is restored correctly, but the password is null because it was skipped during serialization.
  • This shows how transient helps exclude sensitive or unnecessary data from being stored or transmitted.

When to use transient in Java? 

  • When data members were derived from other data members inside the same class instance, the transient modifier is used.
  • It can be applied to data members that don’t show the object’s current state.
  • Also, non-serialized objects or classes can utilize transient modifiers for their data members.

Looking to strengthen your Java skills with a solid understanding of object-oriented programming? upGrad’s free Java Object-oriented Programming course helps you grasp key concepts like classes, objects, inheritance, polymorphism, encapsulation, and abstraction through hands-on examples.

Also ReadSerializable Interface in Java with Examples

Now that you understand the working of the transient keyword in Java, it is important to see transient vs volatile java.

Transient vs Volatile Java

In Java, transient and volatile are two crucial keywords that affect how variables behave at runtime, but they serve very different purposes.

  • transient is related to serialization. It prevents a variable from being saved when an object is serialized.
  • volatile is related to multi-threading. It ensures visibility of changes to variables across threads.

Understanding the distinction is essential when dealing with data persistence and concurrent programming. Let’s explore their differences, examples, and appropriate use cases.

Feature / Aspect transient volatile
Purpose Exclude a field from serialization Ensure visibility of changes across threads
Used In Object serialization Multithreading/concurrency
Belongs To java.io package java.util.concurrent concept (JVM level)
Affects Persistence and storage of object state Memory visibility of shared variables
Impact on JVM Behavior Skips the field during object serialization Forces read/write to main memory
Use Case Skip saving sensitive info (e.g., password) Coordinate access to shared variables in threads
Fails When Data is needed after deserialization Not used with atomic operations or synchronization
Keyword Type Modifier used in the serialization context Modifier used in a concurrency context

Code Example: transient Keyword in Java

import java.io.*;

class User implements Serializable {
    String username;
    transient String password; // This won't 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("alice", "secret123");

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

        // Deserialize
        ObjectInputStream in = new ObjectInputStream(new
FileInputStream("data.ser"));
        User savedUser = (User) in.readObject();
        in.close();

        System.out.println("Username: " + savedUser.username); // alice
        System.out.println("Password: " + savedUser.password); // null (not serialized)
      
    }
}

Code Explanation: The password field is marked as transient, so it is not saved when the object is serialized. When the object is deserialized, the password is null.

Output:

Username: alice
Password: null

Output Explanation:

  • Username: alice. The username field was serialized and then deserialized correctly.
  • Password: null. The password field was marked transient, so it was skipped during serialization. On deserialization, its value becomes null.

Code Example: volatile Keyword


class SharedData {
    volatile boolean flag = false;

    public void writer() {
        flag = true; // change is immediately visible to other threads
    }

    public void reader() {
        if (flag) {
            System.out.println("Flag has been updated by another thread.");
        }
    }
}

Code Explanation: The flag variable is declared volatile. This ensures that when one thread updates the flag's value, the change is visible immediately to all other threads. Without volatile, threads might cache the variable and never see the updated value.

Output:


Flag has been updated by another thread.

Output Explanation: Because the flag is declared volatile, the update by writerThread becomes immediately visible to readerThread, which then prints the message.

Use Cases:

Use transient when:

  • You want to exclude fields from being persisted or transferred.
  • Fields contain sensitive or temporary information (e.g., passwords, session tokens).
  • The data can be recalculated or is not needed post-deserialization.

Use volatile when:

  • You’re working with shared variables in a multithreaded application.
  • You want to ensure each thread sees the latest value of a variable.
  • You need lightweight visibility control but not full synchronization.

Also ReadA Complete Guide to Keywords in Java

Now that you understand how the transient keyword differs from volatile, let’s explore how the transient keyword in Java behaves in a real-world scenario through a detailed example that simulates object serialization and deserialization.

Understanding the Transient Keyword in Java Through a Complex Example

The transient keyword in Java becomes especially important when dealing with complex Java classes that include sensitive or temporary data you don’t want to persist during serialization. In real-world applications, such fields may consist of passwords, session tokens, cache data, or computed values that can be regenerated. This section walks you through a detailed example to help you understand how transient works in multi-field objects.

import java.io.*;

class Session implements Serializable {
    private String sessionId;
    private transient long lastAccessTime;

    public Session(String sessionId, long lastAccessTime) {
        this.sessionId = sessionId;
        this.lastAccessTime = lastAccessTime;
    }

    @Override
    public String toString() {
        return "Session ID: " + sessionId + ", Last Access Time: " + lastAccessTime;
    }
}

public class TransientComplexExample {
    public static void main(String[] args) {
        Session session = new Session("ABC123", System.currentTimeMillis());

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("session.ser"));
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("session.ser"))) {

            oos.writeObject(session);

            Session deserializedSession = (Session) ois.readObject();
            System.out.println("Deserialized Session: " + deserializedSession);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Code Explanation:

  • Serializable: The Session class implements Serializable, which means its objects can be converted into a byte stream and stored or transferred.
  • transient: The lastAccessTime field is marked as transient, meaning it will not be included in the serialization process. When the object is deserialized, this field will be reset to its default value (0 for long).
  • Serialization: The object is written to a file session.ser using ObjectOutputStream.
  • Deserialization: The same object is then read back using ObjectInputStream. Since lastAccessTime is transient, its value is not restored from the file.

Output:

Deserialized Session: Session ID: ABC123, Last Access Time: 0

Output Explanation:

  • sessionId was serialized and thus restored correctly.
  • lastAccessTime was skipped due to the transient keyword, so it defaults to 0 during deserialization.

Also ReadIs Java Easy to Learn? Common Challenges and How to Overcome Them

Now that you’ve seen a complex example of the transient keyword in Java, let’s explore some essential tips and best practices to use it effectively in your projects.

 

Tips and Best Practices for Using the Transient Keyword in Java

When working with the transient keyword in Java, following best practices ensures your serialization process is secure, efficient, and behaves as expected. Proper transient use helps protect sensitive data, manage temporary fields, and maintain data integrity during serialization and deserialization. 

Additionally, understanding how to customize serialization and the role of the Serializable interface is crucial for advanced control.

  • Protect Sensitive Data: Use the transient keyword in Java to exclude sensitive information such as passwords or credit card numbers from being serialized and potentially exposed.
  • Handle Temporary Data: Mark fields as transient if they contain temporary or cache data that can be recalculated after deserialization, so they don’t unnecessarily persist.
  • Be Aware of Default Values: Transient fields are reset to default values during deserialization (e.g., zero for numbers, null for objects), so plan accordingly.
  • Implement Serializable: Make sure your class implements the Serializable interface; otherwise, transient fields have no impact during serialization.
  • Test Thoroughly: Always test serialization and deserialization processes to verify that transient fields behave as expected.
  • Understand Static Fields: Static fields belong to the class and are never serialized, so marking them transient does not affect their behavior. 
  • Customize Serialization: For advanced control, implement the writeObject and readObject methods to add custom serialization or deserialization logic:
private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject();
    // Add your custom serialization logic here
}

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

Also ReadTop 8 Reasons Why Java is So Popular With Developers in 2025

With a solid grasp of best practices, let’s explore real-world scenarios in which using the transient keyword in Java can significantly improve your Java applications.

Use-cases for the ‘transient’ Keyword in Java

Now that you understand the transient keyword in Java and what it does, the next logical question that arises is – when do we use the transient keyword?

Let’s expand our learnings about the transient keyword by looking deeply at some of the situations where you would benefit from using the transient keywords.

Here are some commonly encountered use-cases for you to keep in mind: 

  • The first use-case of transient keyword in Java is during situations where you might have data fields that are either calculated or derived from some other fields within the class’ instance. As a result, these fields need to be calculated programmatically, and they depend on other values. That is why, instead of having such fields persistent, they could be non-serialized using the transient keyword. Examples of such transient values calculated from other figures could include time-stamp-based values, percentages-based values, etc. In all these cases, you are calculating the value of a variable based on currently existing values.
  • Another important use-case could be when you are working with any type of secure information that should not, in any case, be leaked outside the JVM, then that can be non-serialized using the transient keyword. 
  • Fields that are not marked “serializable” inside the Java Development Kit can be used with a transient keyword. An important thing to note here is that all Java classes that do not implement the serializable interface cannot be serialized since they are not referenced within any serializable class. As a result, these might throw “java.io.NotSerializableException” if not marked “transient” before serializing the main class.
  • And finally, there are some occasions where it doesn’t make sense to serialize some fields. For example, if you have added a logger reference in your code, you wouldn’t want to serialize that information. You should serialize information that represents the state of an instance. Loggers, on the other hand, don’t represent any state, so there is no use in serializing them. Thus, they should be used with the transient keyword in Java.

Conclusion

The transient keyword in Java controls the serialization process by excluding specific fields from being saved or transmitted. By understanding how transient works and applying it correctly, you can effectively protect sensitive data, optimize performance, and handle temporary or recomputable fields. Whether working with simple objects or complex serialization scenarios, transient helps you write more secure and efficient Java applications.

If you're ready to sharpen your programming skills and create robust applications, here are some additional upGrad programs that can help you upskill and put your learning into action.

If you're ready to take the next step in your careerconnect with upGrad’s career counseling for personalized guidance. You can also visit a nearby upGrad center for hands-on training to enhance your generative AI skills and open up new career opportunities!

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

References:
https://www.pluralsight.com/resources/blog/upskilling/top-programming-languages-2025

Frequently Asked Questions

1. What exactly does the transient keyword do in Java serialization, and why should I use it?

2. Can you explain how transient fields behave when an object is deserialized in Java?

3. How is the transient keyword in Java different from the volatile keyword in Java?

4. Can I use transient with static fields in Java? Does it make sense?

5. What happens if I forget to implement Serializable in a class with transient fields?

6. How do I handle sensitive data like passwords using the transient keyword during serialization?

7. Can transient fields be serialized using custom methods like writeObject and readObject?

8. How does the transient keyword affect performance during serialization and deserialization?

9. Are there any limitations or pitfalls when using transient with inheritance and serialization?

10. Can I use transient fields in combination with Java’s Externalizable interface?

11. How do I test and debug issues related to transient fields in my serialized objects?

Pavan Vadapalli

900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months