Latest Tutorials| Questions and Answers|Ask Questions?|Site Map

Home Java Example Java Util Transient Java Keyword

Related Tutorials


Share on Google+Share on Google+

Transient Java Keyword

In this section we will discuss about transient keyword in java. Transient is a keyword in java which is used to prevent any variable being serialized

Transient Java Keyword

In this section we will discuss about transient keyword in java. Transient is a keyword in java which is used to prevent any variable being serialized. Before going into details about transient we will try to learn about serialization in java. Serialization is used to save the state of object by JVM and during deserialization it is recovered. Serialization save the state of object but if we don't want to make the property of an object serialized we can do it by using transient.

Why do we need transient?

Transient keyword provide you a control on serialization process in java and allow to exclude some of the object properties which you don't want to in serialization process.

Which variable should mark as transient?

By making a variable transient it will not involve in serialization process hence the variable whose value can be calculated from another variables doesn't require to be saved should be marked as transient.

Some of the important facts about transient are as follows :

  • Transient is used with variable or field only.
  • Transient variable in java is not saved because it is not serialized.
  • You can make a variable both transient and static but doing so is not meaningful. Transient does not allow you to serialize and static is not saved during serialization.

Syntax :

 transient data-type variable-name;

Example :

class Demo1 implements Serializable{
    private String Name;
    private transient String address;  //making address transient is not serialized
   public Demo1(){}
    public Demo1 (String Name,String address)
        this.Name = Name;
   public void display()
	   System.out.println("Name = "+Name);
       System.out.println("Address = "+address);
public class MainDemo
    public static void main(String args[]) throws Exception 
        Demo1 ob = new Demo1("Roseindia","Rohini");
        ObjectOutputStream o = new ObjectOutputStream
                   (new FileOutputStream("Demo"));
        // writing to object
       ObjectInputStream in=new ObjectInputStream(new FileInputStream("Demo"));
        Demo1 ob1=(Demo1)in.readObject();

Output :  After compiling and executing the program.

Download Sourcecode


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 3, 2013

Related Tutorials

Discuss: Transient Java Keyword  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image