< Prev
Next >

Transient Keyword

What is "transient"?

In Java, transient is a keyword. When an object is being serialized, its instance variables declared with transient keyword are skipped by the process of Serialization, . i.e. the state of transient instance variable in an object not saved when this object state is serialized by the process of Serialization.

Why "transient" is used?

In some situations, we may not want to save the state of a few unimportant instance variables of an object, when this object is serialized. In this case, we only need to declare these instance variables with the keyword transient.

What happens to an instance variable with "transient" keyword in Serialization?

After an object's state is saved by the process of serialization, when this saved object is deserialized, its instance variables marked with transient are assigned their default values. Such default values are implicitly given to instance variables on an object, when they are not explicitly initialized with a value.

  • Instance variable type
  • Default value
  • boolean
  • false
  • byte, short, int, long
  • zero
  • float,double
  • 0.0
  • character
  • '\u0000'
  • Object reference variable
  • null

    Let's understand "transient" with an example -:

    import java.io.*;
    class TransientExm implements Serializable	//implementing Serializable interface 
    transient int i=10;	//instance variable of type primitive is marked "transient"
    public static void main(String... ar)
    TransientExm ob= new TransientExm();
    System.out.println("Before Serialization object has value : " + ob.i);
    	//Writing saved state of the object in this file
    	FileOutputStream fos= new FileOutputStream("E:\\File.ser");
    	ObjectOutputStream oos= new ObjectOutputStream(fos);
    	//Serializing, i.e. saving the state of this object, ob
    catch(Exception exp)
    	//Reading the same file for Deserialization
    	FileInputStream fis= new FileInputStream("E:\\File.ser");	
    	ObjectInputStream ois= new ObjectInputStream(fis);
    	//Deserializing, i.e. restoring the object to its original state.
    	System.out.println("After Deserialization restored object has value : "+ ob.i);
    catch(Exception exp)

    Output is -:

    Before Serialization object has value : 10
    After Deserialization restored object has value : 0

    Program Analysis

    Please share this article -

    Facebook Google Pinterest Reddit Tumblr Twitter

    < Prev
    Next >
    < What is Serialization?
    Static in Serialization >

    Please Subscribe

    Please subscribe to our social media channels for daily updates.

    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page