×

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 Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.