Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Transient Keyword in Java
3.
How to Use Transient Keyword in Java?
4.
When to use the transient keyword?
5.
Where to Use the Transient Keyword?
6.
Syntax of Transient Keyword
7.
Example of Java Transient Keyword
7.1.
Java
8.
Transient with Final Keyword
8.1.
Java
9.
Transient with Static Keyword
9.1.
Java
10.
Benefits of using Transient Keyword in Java
11.
Difference Between Transient and Volatile Keyword in Java
12.
Frequently Asked Questions
12.1.
What is Serialization?
12.2.
What is the use of the Transient keyword in Java?
12.3.
What is transient and static keyword in Java?
12.4.
What is the effect of using the Transient keyword with Static Keyword?
13.
Conclusion
Last Updated: Mar 27, 2024
Medium

Transient Keyword in JAVA

Author Jay Dhoot
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Do you know that there is a variable modifier called 'transient' in Java? Do you know that the transient modifier is used in serialization?

Transient Keyword in JAVA

Transient keywords are generally used with those data members who have confidential information within them. In this article, we will learn about transient keywords in Java. We will also see the syntax and usage of the keyword.

Also read, Duck Number in Java and Hashcode Method in Java.

Transient Keyword in Java

The transient keyword is used when we do not want the variable to be serialized, i.e., we do not want the value of that variable to be stored in a file. Whenever JVM sees the transient keyword, it ignores the original value of the value and just stores the default value of the same.

Serialization and De-Serialization
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to Use Transient Keyword in Java?

In Java, the transient keyword is used in the context of serialization to indicate that a variable should not be included in the serialization process. Here's how to use it:

1. Declare a Variable as Transient:

import java.io.Serializable;
public class MyClass implements Serializable {
   private transient int transientVar;
   private String nonTransientVar;
   // Constructors, methods, etc.
}

 

Marking a variable as transient in a class that implements Serializable means that the variable won't be included when the object is serialized.

2. Serialization and Deserialization:

import java.io.*;
public class SerializationExample {
   public static void main(String[] args) {
       // Serialization
       try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myObject.ser"))) {
           MyClass myObject = new MyClass();
           oos.writeObject(myObject);
           System.out.println("Object Serialized");
       } catch (IOException e) {
           e.printStackTrace();
       }
       // Deserialization
       try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myObject.ser"))) {
           MyClass deserializedObject = (MyClass) ois.readObject();
           System.out.println("Object Deserialized");
       } catch (IOException | ClassNotFoundException e) {
           e.printStackTrace();
       }
   }
}

 

When the object is serialized, the transientVar won't be included in the resulting byte stream. Upon deserialization, the transientVar will be assigned its default value.

When to use the transient keyword?

We can use the transient keyword when:

  • Sensitive Data: Use transient for variables that contain sensitive information (e.g., passwords) to avoid exposing them during serialization.
     
  • Derived Data: If a variable can be derived or calculated from other variables, making it transient can reduce the amount of data transmitted or stored.
     
  • Caching: For variables that can be recalculated or fetched from a cache, marking them as transient avoids unnecessary serialization and deserialization overhead.
     
  • Static or Non-Serializable Fields: Variables declared as static or non-serializable (e.g., file handles) can be marked as transient to exclude them from serialization.
     
  • Performance Optimization: Use transient for large objects or variables that don't need to be persisted, optimizing the serialization process.

Where to Use the Transient Keyword?

There are various real-life examples where we do not want to save private data like passwords, atm pins, etc., and this is where transient keyword play an important role. The transient keyword is generally used with the variables that are needed to be kept secured or with the ones whose value can be derived from other serialized objects. For example, the age of a person.

Consider the example of an object where we have a password stored in a variable. While serializing the object in a byte stream, we don't want the password to be stored on the hard disk. So for the password variable, we can use the transient keyword as it would avoid serialization of that particular variable. Whenever JVM would come across the transient keyword, it would ignore the original value of the password and would just store the default value of the same.

Also read, Swap Function in Java

Syntax of Transient Keyword

The transient keyword can be used by just writing the transient keyword while defining a variable.  

For example:

class tran{
	//code 
	transient Int pin;
	//code
}


It is a good practice to use the transient keyword with the private keyword while storing private, confidential information.

Syntax:

transient private <variable>;  


Or 

private transient <member variable>;    

Example of Java Transient Keyword

Consider the example of a Ninja class with three data members' name, email, and password. As the password needs to be kept secure, we have used the transient keyword. Use of transient keyword would not allow the password to be serialized, so a default value would be stored.

The below code implements a class Ninja, and it first serializes and then deserializes the Ninja object.

Code  

 

  • Java

Java

import java.io.*;      
public class Ninja implements Serializable{  
 
String name;
String email;
//Will not be serialized

transient String password;

//Constructor
//Initializes the object
public Ninja(String name, String email, String password) {  
  this.name = name;   
  this.email = email;   
  this.password=password;   
}

public static void main(String args[])throws Exception{
  //New Student Object
  Ninja C =new Ninja("Ninja1","coding.ninja@gmail.com","CN!@1");

  //Serialization  
  FileOutputStream cn=new FileOutputStream("cn.txt");   
  ObjectOutputStream out=new ObjectOutputStream(cn);   
  out.writeObject(C);   
  out.flush();   
  out.close();   
  cn.close();  
   
  System.out.println("Serialized Student Object");

  //Deserialization
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("cn.txt"));   
  Ninja c=(Ninja)in.readObject(); 
 
  System.out.println("Deserialized Student Object:");
  System.out.println("Name: "+c.name+" ;"+"E-mail: " +c.email+" ;"+"Password: "+c.password);   
 
  in.close();
}
}  


Output

Output

Transient with Final Keyword

Variables with the final keyword are Constant. Their values can not be changed after initialization. The Transient keyword can be combined with the Final keyword. The final variables can be initialized in either of the two ways:

  1. Explicit declaration: In this, the variables are initialized at the time of its declaration. Using the transient keyword with the final keyword has no effect here, as during the serialization process, the values are directly serialized.Consider the below example, we have declared the variable age explicitly, and in the output, we can see that its value is restored.
     
  2. Parameterized constructor: In this, the variables are declared inside the constructor. When serialization of the object occurs, all final transient variables will not be serialized, and after the deserialization process, these final transient variables will be assigned their default values. Consider the below example, we have declared the variable password in the parameterized constructor, and in the output, we can see that it gets restored to its default value(which is null in this case).


For example,

Code   

  • Java

Java

import java.io.*;      
public class Ninja implements Serializable{   
String name;
String email;

//Explicit Declaration
//Will be serialized
final transient int age=18;

//Parametrized Declaration
//Will not be serialized
final transient String password;

//Constructor
//Initializes the object
public Ninja(String name, String email, String password) {  
  this.name = name;   
  this.email = email;   
  this.password=password;   
}

public static void main(String args[])throws Exception{
  //New Student Object
  Ninja C =new Ninja("Ninja1","coding.ninja@gmail.com","CN!@1");

  //Serialization  
  FileOutputStream cn=new FileOutputStream("cn.txt");   
  ObjectOutputStream out=new ObjectOutputStream(cn);   
  out.writeObject(C);   
  out.flush();   
  out.close();   
  cn.close();   
 
  System.out.println("Serialized Student Object \n");

  //Deserialization
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("cn.txt"));   
  Ninja c=(Ninja)in.readObject(); 
 
  System.out.println("Deserialized Student Object: \n");
  System.out.println("Name: "+c.name+" ;"+"E-mail: " +c.email+" ;"+"Password: "+c.password +" ;"+"Age: "+c.age+"\n");
  System.out.println("Varibale Age gets serialised as it is declared explicitly");
  System.out.println("Variable password does not get serialized and is restored with its default value.");
 
  in.close();
}


Output

Output

Transient with Static Keyword

The Transient keyword can be combined with the Static keyword. As static variables are not a part of the object's state, there is no impact of using transient keywords with them and its default value is restored.
In the below example, variable school has the static and the transient keyword, however in the output we can see that its default value is restored.

Example:   

  • Java

Java

import java.io.*;      
public class Ninja implements Serializable{   
String name;
String email;

//No impact of transient here
static transient String school="CN";

//password will be serialized
transient String password;

//Constructor
//Initializes the object
public Ninja(String name, String email, String password) {  
  this.name = name;   
  this.email = email;   
  this.password=password;   
}

public static void main(String args[])throws Exception{
  //New Student Object
  Ninja C =new Ninja("Ninja1","coding.ninja@gmail.com","CN!@1");

  //Serialization  
  FileOutputStream cn=new FileOutputStream("cn.txt");   
  ObjectOutputStream out=new ObjectOutputStream(cn);   
  out.writeObject(C);   
  out.flush();   
  out.close();   
  cn.close();   
 
  System.out.println("Serialized Student Object \n");

  //Deserialization
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("cn.txt"));   
  Ninja c=(Ninja)in.readObject(); 
 
  System.out.println("Deserialized Student Object: \n");
  System.out.println("Name: "+c.name+" ;"+"E-mail: " +c.email+" ;"+"Password: "+c.password +" ;"+"School: "+c.school+"\n");
  System.out.println("Varibale School has no impact of transient keyword and returns its default value");
 
  in.close();
}


Output

Output


Also read, Java Ioexception

Benefits of using Transient Keyword in Java

There are many benefits of using the transient keyword in Java:

  1. Improved Security: Transient keyword helps in preventing the Serialization of the objects and also prevents storing their values. This helps prevent unauthorized access to sensitive data like passwords, atm PINs, etc.
     
  2. Faster Performance: The use of transient keywords prevents the Serialization of variables, thereby making the serialization process faster as fewer data need to be serialized.
     
  3. Reduced Size of Byte Stream: In Serialization, an object gets converted into a byte stream. As transient variables are not serialized, the byte stream's size is considerably reduced.

Difference Between Transient and Volatile Keyword in Java

Feature transient Keyword volatile Keyword
Purpose Used in the context of serialization. Ensures visibility and atomicity of a variable's value in a multithreaded environment.
Usage Applied to instance variables in a class. Applied to instance variables.
Serialization Excludes the variable from the serialization process. No specific impact on serialization.
Thread Safety Does not address thread safety. Ensures visibility but does not guarantee atomicity for compound operations.
Visibility Guarantee Does not guarantee visibility or atomicity in a multithreaded environment. Ensures visibility and atomicity for simple read and write operations.
Use Case Prevents certain variables from being serialized (e.g., sensitive information). Ensures the latest value of a variable is visible to all threads.
Example private transient int sensitiveData; private volatile boolean flag;

Read More,  even number program in java

Read more, how to run java program

Frequently Asked Questions

What is Serialization?

Serialization in Java is converting an object into a byte stream. The byte stream stores both the data of the instance and its type. This byte stream is stored in a file that can be saved in a hard disk rather than main memory. Deserialization is opposite to Serialisation. It converts the byte stream into original object data.

What is the use of the Transient keyword in Java?

The transient keyword in Java prevents a variable from getting serialized. Whenever Java Virtual Machine(JVM) sees the transient keyword, it ignores its original value and just stores the default value of the same.

What is transient and static keyword in Java?

transient keyword used in serialization. It marks a variable not to be serialized. It prevents sensitive or unnecessary data from being persisted. On the other hand, static keyword is associated with class rather than instances. It is shared among all instances. It is used for constants, methods, or shared resources.

What is the effect of using the Transient keyword with Static Keyword?

The Transient keyword can be combined with the Static keyword. As static variables are not a part of the object's state, there is no impact of using transient keywords with them and its default value is restored.

Conclusion

In this article, we have discussed the Transient keyword in Java with its example. To learn more about error and exception, you can refer to the below-mentioned article:

Difference between Error and Exception

We hope this article has helped you understand the transient keyword. If this article helped you in any way, then you can read more such articles on our platform, Coding Ninjas Studio. You will find articles on almost every topic on our platform. Also, for cracking good product-based companies, you can practise coding questions at Coding Ninjas. For interview preparations, you can read the Interview Experiences of popular companies.

Previous article
IntelliJ vs Eclipse
Next article
Java vs Python and C++
Live masterclass