×

Java Transient

Java Transient

In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the type of data stored in that instance. Deserialization performs exactly opposite operation. It converts the byte sequence into original object data.During the serialization, when we do not want an object to be serialized, we can use a transient keyword.

The following program shows how serialization is performed.

SampleSerialize.java

 import java.io.*;
/* serializable class */
class Employee implements java.io.Serializable
{
   public String empname;
   public String empaddress;
   public int emppassword;
   public int empid;
   public void mailCheck()
   {
System.out.println("Check a mail to " + empname + " " + empaddress);
   }
}
public class SampleSerialize
{
/* Driver Code */
   public static void main(String [] args)
   {
      Employee e = new Employee();
e.empname = "ABC";
e.empaddress = "XYZ";
e.emppassword = 11122333;
e.empid = 401;
      try
      {
FileOutputStreamfileOut = new FileOutputStream("empinfo.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in empinfo.ser");
      }
      catch (IOExceptioni)
      {
i.printStackTrace();
      }
   }
} 

Output:

Serialized data is saved in empinfo.ser

In the above code, the Employee class is serialized and the serialized objects are stored inside the file named empinfo.ser. Here, we do not want to serialize the data member emppassword.

Further in this article, we will be discussing how transient keyword can be used to avoid the serialization of a data member.

Why use the transient keyword?

The transient keyword can be used with the data members of a class in order to avoid their serialization. For example, if a program accepts a user’s login details and password. But we don’t want to store the original password in the file. Here, we can use transient keyword and when JVM reads the transient keyword it ignores the original value of the object and instead stores the default value of the object.

Syntax:

privatetransient<member variable>;

Or

transient private<member variable>;

When to use the transient keyword?

  1. The transient modifier can be used where there are data members derived from the other data members within the same instance of the class.
  2. This transient keyword can be used with the data members which do not depict the state of the object.
  3. The data members of a non-serialized object or class can use a transient modifier.

The following program demonstrates the use of transient keyword.

SampleSerialize.java

 import java.io.*;
/* serializable class */
class Employee implements java.io.Serializable
{
   public String empname;
   public String empaddress;
   public transient int emppassword;
   public int empid;  
   public void mailCheck()
   {
System.out.println(“Check a mail to " + empname + " " + empaddress);
   }
}
public class SampleSerialize
{
   /* Driver Code */
   public static void main(String [] args)
   {
      Employee e = new Employee();
e.empname = "ABC";
e.empaddress = "XYZ";
e.emppassword = 11122333;
e.empid = 401;   
      try
      {
FileOutputStreamfileOut = new FileOutputStream("empinfo.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in empinfo.ser");
      }
      catch (IOExceptioni)
      {
i.printStackTrace();
      }
   }
} 

Output:

Serialized data is saved in empinfo.ser

In the above code, the Employee class is serialized and the serialized objects are stored inside the file named empinfo.ser. Here, we do not want to serialize the data member emppassword. So, to achieve that we have used transient keyword before the data member name. Now if we check the contents of the file empinfo.ser it will have the default value for the transient variable.

Use of transient with final keyword

Consider the Employee class from above example. If we modify the data members of Employee class they will behave differently.

 class Employee implements Serializable
{
public int empid;
   public String empname;
   public String empaddress;
   public transient int emppassword = "123456";
   public final transient Lock lock = Lock.getLock("demo");
} 

Output:

 401
ABC
XYZ
123456
null 

Here, all the other data members are returning the values as they are initialized. Even though we have used thetransient property for the emppassword variable, it is behaving like the other data members. This is because when a final data member is initialized the JVM reads it as a constant expression and performs serialization operation on it. But in the similar case of thelock, it is not serialized because it is a reference.

In this article, we have discussed the concept of serialization in Java, use of transient keyword, where to use transient keyword and how it behaves differently when used with the final keyword.


Related Topics

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

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

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.