Do you think IIT Guwahati certified course can help you in your career?
No
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 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.
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.
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.
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.
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.
Implementation
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");
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:
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.
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,
Implementation
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");
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(); } }
You can also try this code with Online Java Compiler
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");
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(); } }
You can also try this code with Online Java Compiler
There are many benefits of using the transient keyword in Java:
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.
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.
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.
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 are 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 the 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 errors and exceptions, you can refer to the below-mentioned article:
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.