×

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both included in the byte stream. Deserialization does the exact opposite task. The byte sequence is changed into the original object data. When we don't want an object to be serialized during serialization, we can use a temporary keyword.

A variable modifier used in serialization is transitory. The temporary keyword is used during serialization if we don't want to save the value of a certain variable in a file. When JVM encounters a temporary keyword, it discards the variable's original value and saves the default value for that variable's data type.

The use of temporary keywords is crucial for observing security restrictions. There are many situations in real life where we don't want to save private information in a file. The transient keyword can also be used to avoid serializing variables whose values can be calculated or deduced from other serialized objects or systems, such as a person's age, the current date, etc.

Practically, we only serialized the fields that represented an instance's state; after all, the entire point of serialization is to store an object's information to a file. Use of the transitory keyword with a class's private, confidential fields during serialization is a recommended practice.

Usage of Transient Keyword

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

Syntax:

private transient <variable>;
Or
transient private <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 transitory modifier might be utilized.
  • This temporary keyword can be applied to data members that don't show the object's current state.
  • A temporary modification can be applied to the data members of a non-serialized object or class.

Examples of Transient Keyword

Take the Student class, for instance, which has the three data members’ id, name, and age. All the values in the object will be serialized if you serialized it, but if there are any variables, like age, that you don't want to serialize, you can define the age data member to be transitory. Two classes, Student and Persist Example, have been defined for this example. Since the Student class's age data component is marked as temporary, its value will not be serialized.

You will receive the transitory variable's default value if you deserialize the object.

Let's make a class that contains temporary variables.

import java.io. *;      
public class Stud implements Serial {    
 int roll;
 String name;
 transient int ag;//here it is unable to be serialized    
 public Stud(int roll, String name,int ag) {    
this. roll = roll;
  this.name = name;
  this.ag=ag;
 }    
}    
class Persist Ex {    
 public static void main(String s[])throws Exception{    
  Stud st1 =new Stud(211,"ravi",22);//object is created
  //writing object into file    
  FileOutStream ss=new FileOutStream("ss.txt");
  ObjectOutStream out=new ObjectOutStream(ss);
Out. WriteObj(st1);
out. Flush();
out. Close();
ss. close();
  System.out.println("success");
 }    
}    

Output:

Success

Static fields are not a part of an object's state, hence using the transitory keyword with static variables serves no purpose or has no negative effects. There isn't a compilation error, though.

Transient and final variables are not used or affected by each other since final variables are directly serialized by their values. However, there isn't a compile-time error.

Create the deserialization code: import java.io. *;   

class Depersis {    
 public static void main (String s []) throws Exception {    
  Object In Stream inp=new Object inStream (new FileinStream("ss.txt"));
  Stud ss=(Stud)inp. readObject ();
  System.out.println(ss. roll+" "+ss.name+" "+ss.ag);
in. close ();
 }    
}    

Output:

211 Ravi 0

As you can see, printing the student's age yields a value of 0 because age was not serialized.

The use of the transitory keyword in Java, appropriate contexts for its use, and how to apply it in Java programmers have all been covered in this article.


Related Topics

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.