×

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

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

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

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.