Transient Keyword in Java: What is it & How it Works?
Updated on May 28, 2025 | 20 min read | 10.76K+ views
Share:
For working professionals
For fresh graduates
More
Updated on May 28, 2025 | 20 min read | 10.76K+ views
Share:
Table of Contents
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!
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:
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();
}
}
}
Explanation:
Output:
Serialized user: User{username='john_doe', password='mySecret123'}
Deserialized user: User{username='john_doe', password='null'}
Output Explanation:
When to use transient in Java?
Also Read: Serializable 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.
In Java, transient and volatile are two crucial keywords that affect how variables behave at runtime, but they serve very different purposes.
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:
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:
Use volatile when:
Also Read: A 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.
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:
Output:
Deserialized Session: Session ID: ABC123, Last Access Time: 0
Output Explanation:
Also Read: Is 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.
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.
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 Read: Top 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.
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 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 career, connect 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
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
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
Top Resources