Programs

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:

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

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.

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

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

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

Want to share this article?

Lead the AI Driven Technological Revolution

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks