×

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 Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

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

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.

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.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

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

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.