What is transient keyword in Java?

This article explains about the transient variable and when it will be used in the Java programming. Another important fact is that, this question is most frequently asked in the Java interviews for checking the basic knowledge of a programmer. Another point is that this keyword is not frequently used by programmer in the normal world, unless the real need for that. That makes practical knowledge on this keyword is minimal for most of the programmers. This article explores with very simple explanations and example to make you understand when and why transient variable will be used in Java.   If you are Java programmer and want to receive the weekly updates on Java tips to improve your knowledge, please subscribe to our free newsletter here.

also read:

What is Serialization?

If you want to understand what is transient, please learn about what is Serilization concept in Java if you are not familiar with that. Serialization is the process of making the object’s state is persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object’s state from bytes. This is one of the important concept in Java programming because this serialization is mostly used in the networking programming. The object’s which are needs to be transmitted through network has to be converted as bytes, for that purpose every class or interface must implement  serialization interface. It is a marker interface without any methods.

What is Transient?

The keyword transient in Java used to indicate that the variable should not be serialized. By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.

Transient Keyword Example

Look into the following example to understand the purpose of transient keyword:

package javabeat.samples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class NameStore implements Serializable{
	private String firstName;
	private transient String middleName;
	private String lastName;
	public NameStore (String fName,
                         String mName,
                         String lName){
		this.firstName = fName;
		this.middleName = mName;
		this.lastName = lName;
	}
	public String toString(){
		StringBuffer sb = new StringBuffer(40);
		sb.append("First Name : ");
		sb.append(this.firstName);
		sb.append("Middle Name : ");
		sb.append(this.middleName);
		sb.append("Last Name : ");
		sb.append(this.lastName);
		return sb.toString();
	}
}
public class TransientExample{
	public static void main(String args[]) throws Exception {
		NameStore nameStore = new NameStore("Steve",
                                     "Middle","Jobs");
		ObjectOutputStream o = new ObjectOutputStream
                   (new FileOutputStream("nameStore"));
		// writing to object
		o.writeObject(nameStore);
		o.close();

		// reading from object
		ObjectInputStream in =new ObjectInputStream(
                new FileInputStream("nameStore"));
		NameStore nameStore1 = (NameStore)in.readObject();
		System.out.println(nameStore1);
	}
}
// output will be :
First Name : Steve
Middle Name : null
Last Name : Jobs

In the above example, the variable middle Name is declared as transient, so it will not be stored in the persistent storage. You can run the above example and check the results.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

  • praneeth

    your explanation is good pls give program explanation also

  • Amit

    Why dont you want to persist the middle name?

    • Vinay Wadhwa

      Its just an example to explain the meaning of Transient keyword.

      • http://www.javabeat.net Krishna Srinivasan

        Yes. It is just an example to use the Transient keyword. If you have any suggestions, please post it here. Thank you for the comments.

  • Rizwan

    In Swing/AWT i tried to serialize JPanel which is using GroupLayout. Unfortunatelly GroupLayout can not be serialized, so i try to set it's decleration with transient keyword. but this does not change anything? Why is that so, it only works if i remove grouplayout altogether, just declaring transient does not work… What could be the reason??

    • Ali

      You can serialize JPanel properties (fields,…), and when deserialize create JPanel with the saved properties .

      The use of transient is to tell the serialization mechanism that the field should not be saved along with the rest of that object's state.

      • Ali

        i mean GroupLayout

  • http://www.babaniyi.ws Ayodeji Babaniyi

    Excellent explanation! I like explanations like this, reveals the complete truth about the transient keyword.

  • Eee

    Serilization = Serialization”That means the state of the object is converted into stream of bytes and stored in a file.”
    Maybe you meant “in a byte stream”?
    Stopped reading on this sentence.

  • http://twitter.com/Kjellski Kjell Otto

    Please correct the horrible grammar in this article. It will make people think that you are sloppy.

    • Jonathan

      Nicely explained but indeed please correct the grammar.

      • Krish

        Done some update on the post. It was written without much thought, :)

  • Pingback: Java中的transient关键词()

  • http://www.facebook.com/preemptif Zakaria Bouazza

    A part from the ”Serilizition” , everything seems ok

    • Krish

      Thank you for pointing out the problem, I have updated it :)

  • http://www.facebook.com/khaled.sobhy.7 Khaled Ahmed Sobhy

    perfect thanks.. I have a question though.. new FileOutputStream(“nameStore”), new FileInputStream(“nameStore”).. where is the file extension? should it be.txt? I saw.ser extension in an article once.. I see it here completely ignored.. someone explain please..

    • Krish

      Are you getting any error?. There is no need for providing the extension.

  • muthuselvan

    nice explanation

  • devendra

    nice but just it’s joking

  • devendra

    nice but just it’s joking

  • devendra

    nice but just it’s joking

  • devendra

    nice but just it’s joking

  • devendra

    nice but just it’s joking

  • Hoang Le

    It likes [XmlIgnoreAttribute] in C# when using XmlSerializer.
    http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx

  • Raghvendra

    A good explanation of transient keyword thanks:)

  • Neville

    I learned something else today, thanks…. Never came across the transient keyword so far.

  • Nirmal Mangal

    Krishna, Article is good and clears the concept.
    However Please try to resolve the grammer issue, no offence but people will not take it seriously until grammer is fixed.

    • krishnas

      Hello Nirmal,

      Thank you for the comments. I have updated the content.

      Thanks,
      Krishna

  • mikesmullin

    surprisingly clear article despite the grammatical issues. thx!

    • krishnas

      HI,

      Thank you for the comments!!

      Thanks,
      Krishna

      • veerareddy

        what prospers xsd in the webservices ?
        09654457708

  • Pingback: MSQLite library | Michal Dabski()

  • Pingback: Java Scanner Class With Examples()

  • http://javadomain.in Diva

    you can find some more details in the below link,”http://javadomain.in/transient-in-java-with-example/”

  • Pingback: serialization & transient | P Laboratory()

  • Pingback: Assertions In Java()

  • Siddu

    final int a=23; // This makes constants
    final int array[]={34,3445,5}; // but this snippet wont make constant but array Objects can make constants.
    how to make individual array elements constant?

  • Aditya Konidena

    Dude you just made my day

    • http://www.javabeat.net Krishna Srinivasan

      Thank you!!

  • Rams

    Thanks Krishna garu,

    It would have been good if you specify some real time uses of the “transient” keyword.

    Thanks,
    Ram

  • Voland

    Great post!