Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconTransient Keyword in Java: What is it & How it Works?

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

Last updated:
1st Jun, 2023
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Transient Keyword in Java: What is it & How it Works?

Like all other programming languages, Java Programming Language has a list of reserved words that have a specific meaning. This set of 52 words reserved by Java are known as keywords. Since they have a predefined meaning, programmers can’t use keywords to name their classes, objects, variables, and other identifiers. One out of these 52 keywords is the transient keyword – which will be the focus of our blog! 

Check out our free courses to get an edge over the competition 

Transient Keyword in Java

Why Use Transient In Java?

To prevent the serialization of a class’s data members, use the transient keyword with them. For instance, if a program accepts the username and password of a user. The original password, however, should not be kept in the file. Here, we can use the transient keyword, which instructs JVM to ignore its original value and instead store the object’s default value when it reads the keyword.

Syntax 

The syntax to use this keyword can be:

Ads of upGrad blog
  • transient private <member variable>;  
  • private transient <member variable>; 

When To Use The Transient Keyword? 

  • When there are data members that 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.

Differences Between Transient and Volatile keyword

  • Instance variables can be excluded from serialization by using the transient keyword in conjunction with them. The volatile keyword can be used in variables to signal that the JVM and compiler consistently read the value from the main memory and follow the ‘happens-before’ relationship on the visibility of the volatile variable in between various threads.
  • Volatile keywords can be used along with static keywords, but transient keywords cannot be used.
  • During deserialization, transient variables are provided with default values, and the application code must manage their assignment or the value restoration.

Understanding the transient Keyword in Java

Transient is one of the more useful modifiers present in the Java programming language. The primary role of the transient keyword comes in cases of serialization. The transient modifier can be applied to field members of a class to turn off serialization on these specific members. 

Simply put, the transient keyword in Java can be used by the programmer to avoid serialization. If any particular object of any data structure has been defined as transient by the programmer, it will not be serialized. As a result, you can use the transient keyword to indicate to the JVM (Java Virtual Machine) that your transient variable will not be a part of any persistent state of the object. 

Learn Online software development courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Let’s try to understand the working of the transient keyword in Java using a very basic example. First, we’ll create an Address class and define three attributes for the class – streetName, areaName, and houseNumber. We will keep it transient since we don’t want to store or save the third attribute – houseNumber. 

Explore Our Software Development Free Courses

class Address implements Serializable
{
   private String        streetName;
   private String        areaName;
   private transient String houseNumber; 
    //Setters and Getters
}

Now let’s serialize an instance of the Address class.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN) 

try{

   ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("addressinfo.ser"));

   Address a = new Address();

   a.setstreetName("MIG");

   a.setareaName("Vikas Nagar");

   emp.sethouseNumber("110");

   //Serialize the object

   oos.writeObject(a);

   oos.close();

} catch (Exception e)

{

   System.out.println(e);

}

If our code works correctly, the ‘houseNumber’ information would not have been saved since we defined it as transient. Now, we’ll try to deserialize it back into the original object and see if the info was saved or not. 

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

try{

   ObjectInputStream o = new ObjectInputStream(new FileInputStream("addressinfo.ser"));

   //Read the object back

   Address readAddressInfo = (Address) o.readObject();

   System.out.println(readAddressInfo.getstreetName());

   System.out.println(readAddressInfo.getareaName());

   System.out.println(readAddressInfo.gethouseNumber());

   o.close();

} catch (Exception e)

{

   System.out.println(e);

}
If you run the above piece of Java program, you will receive the following output: 
MIG

Vikas Nagar

null

As you can see, ‘houseNumber’ information was not saved to a permanent state because of serialization, and that is why we receive the value ‘null’ as an output. This is precisely why the transient keyword is used – to store values into variables in a manner that is not permanent but transient.

Explore our Popular Software Engineering Courses

Use-cases for the ‘transient’ Keyword in Java

Now that you understand the transient keyword 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 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. 

In-Demand Software Development Skills

  • 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.

Read our Popular Articles related to Software Development

In Conclusion

The use-cases discussed above are by no means exhaustive. Experiment with the transient keyword and come up with your own use cases. After all, keywords are made for programmers, and you’ll be able to make most of the keywords only when you know how they function and what they mean. 

With that, we come to the end of this blog on transient keywords in Java. This is one of the more introductory concepts that you must look to master in order to grow in your software development career. The field of software development is extremely dynamic yet very welcoming if you are ready to pull your socks and put in your best efforts! 

At upGrad, we have mentored and guided students from across the globe, belonging to different domains and helped them kick start their careers in software development. Our PGP in Software Development – Specialisation in Full Stack Development is designed for freshers and experienced professionals. Besides expert tutors and state-of-the-art learning material, you also get talented peers, comprehensive placement support, and one-on-one mentoring with industry leaders. So check out the course content and get yourself registered soon!

What happens when a transient field is accessed after deserialization?

Ads of upGrad blog

On deserializing an object, any transient fields are set to their default values (e.g., null for reference types, 0 for numerical types). You will get its default value if you try to access a transient field after deserialization.

Can the use of a transient keyword impact performance?

Yes, the presence of a transient keyword Java can impact performance, as the serialization and deserialization process skips the transient fields. However, one must understand that the impact is typically small. It is noticeable only in performance-critical applications.

Profile

Pavan Vadapalli

Blog Author
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 strategy.

Frequently Asked Questions (FAQs)

11. What is the transient keyword in Java?

Transient keywords in Java can be used to avoid the serialization of an object. Using transient keywords, you ensure that the value held by the particular field will not be persistent.

22. The transient keyword can be used with what elements in Java?

You can use the transient keyword in Java to non-serialize a class, a variable, an object, or a field.

33. How do the transient keyword and volatile keyword differ in Java?

The transient keyword is used to avoid the serialization process, whereas a volatile keyword is used with a variable so that it’s not stored toin the main memory.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Best Jobs in IT without coding
134253
If you are someone who dreams of getting into the IT industry but doesn’t have a passion for learning programming, then it’s OKAY! Let me
Read More

by Sriram

12 Apr 2024

Scrum Master Salary in India: For Freshers &#038; Experienced [2023]
900303
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers &#038; Experienced [2024]
905056
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5021
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag &#038; Attributes in HTML: Features, Uses, Examples
5133
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5053
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5124
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5058
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions &#038; Answers (Freshers &#038; Experienced)
5138
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon