Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Transient Keyword in Java: What It Is & How It Works

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

In Java language, the transient keyword is an essential part of serialization.  Serialisation converts an object’s state into a format that can be stored or transmitted, typically as a file or stream.  Java serialization is achieved using the serialisable interface and related classes.  The transient keyword is a variable modifier in Java that is used in the context of serialization. This article explained the transient keyword to you.

Introduction to Transient Keyword in Java

In Java, the transient keyword indicates that a particular field should not be serialized. When you serialize an object, the Java language converts it into a byte stream to save it to a file or send it over a network.

 

transient keyword in java

 

How to Use Transient Keywords in Java?

The transient keyword indicates that a field should not be serialized when an object is converted into a byte stream (for example, when saving an object to a file or sending it over a network). It is very useful for fields that contain sensitive or derived values that do not need to be persisted.

class Main{ public static void main(String args[]){ // Code transient String password ; } }

The following program demonstrates the transient keyword example.

 

Program

import java.io.Serializable; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.Date;  public class Employee implements Serializable {  String firstName; String secondName; transient String fullName; String email; String password; Date dob;  /* Constructor */ Employee( String firstName, String secondName, String email, String password, Date dob ) { this.firstName = firstName; this.secondName = secondName; this.email = email; this.password = password; this.dob = dob; this.fullName = firstName + " " + secondName; }  public static void main(String[] args) { Employee student = new Employee( "Harry", "Potter", "harrt.potter@gmail.com", "12345@Nk", new Date() );  serialize(student); deserialize(); }  private static void serialize(Employee student) { try { System.out.println("Student serializing: " + student.toString()); FileOutputStream fileOut = new FileOutputStream("student.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(student); out.close(); fileOut.close(); } catch (IOException i) { i.printStackTrace(); } }  private static void deserialize() { try { FileInputStream fileIn = new FileInputStream("student.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Employee student = (Employee) in.readObject(); in.close(); fileIn.close(); System.out.println("Student deserialized: " + student.toString()); } catch (IOException | ClassNotFoundException i) { i.printStackTrace(); } }  @Override public String toString() { return ( "Student{" + "firstName='" + firstName + ''' + ", secondName='" + secondName + ''' + ", fullName='" + fullName + ''' + ", email='" + email + ''' + ", password='" + password + ''' + ", dob=" + dob + '}' ); } }

Output

Student serializing: Student{firstName='Harry', secondName='Potter', fullName='Harry Potter', email='harrt.potter@gmail.com', password='12345@Nk', dob=Thu Sep 19 10:43:58 IST 2024} Student deserialized: Student{firstName='Harry', secondName='Potter', fullName='null', email='harrt.potter@gmail.com', password='12345@Nk', dob=Thu Sep 19 10:43:58 IST 2024}

After running the following code, a new file named employee.str is generated in the project, which represents the serialized object.

 

We can use the transient keyword with the fullName variable.  When we deserialize the object and inspect the result, we see that the fullName field is null.

 

Also Read: Hybrid Inheritance in Java

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Usage of Transient Keywords in Java

The transient modifier is used to secure the variables. Serialization creates a persistent file. If the object contains passwords or security keys, everything will be saved on the disk, which is not a good sign of a secure system. However, there might be some variables that you do not want to serialize—these are typically sensitive data, derived values, or any data that is not necessary for reconstructing the object. This is where the transient keyword comes into the play.

 

The password variable is critical data, so serialization must be avoided. To skip serialization, we can use the transient keyword in Java.

String firstName; String secondName; transient String fullName; String email; transient String password; Date dob;

How to Use Transient with Final Keyword?

The transient with the final keyword does not affect the serialization because variables declared as final are serialized directly by their values. The final keyword is used to declare constants or restrict the modification of variables, methods, or classes. When we declare the field as final, it can only be assigned once and cannot be changed afterward. It means that the field will not be serialized but its value will remain the same even after deserialization. So, If a field is declared as final, its value will remain the same regardless of whether the object is serialized or not.

Difference between Transient and Volatile Keywords in Java

The following table differentiates the transient and volatile keywords in Java language.

 

Feature transient volatile
Purpose It prevents serialization of a field It ensures the visibility of changes to variables across threads
Use Case It is used in serialization(eg ObjectOutputStream) It used multithreading for shared variables.
Effect The field is not saved during object serialization It changes the variable are visible to all threads immediately.
Thread Safety It does  not provide thread safety It provides limited form of thread safety by ensuring visibility
Keyword Usage Transient is used before the field type Volatile is used before the variable type.

 

Also Read: Method Reference in Java 8

Conclusion

In this article, we learned about the transient keyword in Java language. This keyword is a crucial feature in Object serialization to indicate that certain fields should not be included in the serialized representation of an object. It is particularly useful for protecting sensitive data, such as passwords, ensuring that non-serializable objects are excluded, and avoiding the serialization  of large, resource-intensive fields like file streams. This selective serialization enhances control over data persistence, allowing developers to manage what information is stored, thereby improving security and performance in Java applications. Overall, the transient keyword is essential for effective and secure object serialization.

FAQs
The transient keyword indicates that a particular field should not be serialized when an object is converted into a byte stream. This is useful in excluding sensitive information or non-serializable objects.
Yes, a class can implement the Serializable interface and still contain transient fields. Only the non-transient fields will be serialized.
Yes, we can mark fields of enum types as transient. During serialization these fields will be ignored.
Yes, a class can still be serialized even with transient fields. Only the non-transient fields will be serialized.
brochureimg

The DevOps Playbook

Simplify deployment with Docker containers.

Streamline development with modern practices.

Enhance efficiency with automated workflows.

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved