transient Keyword in Java with Example

transient keyword in Java
transient keyword is a very useful and important keyword that you might have undergone in Serialization. transient keyword is placed in front of a member variable in a class stating that that member variable need not be stored when the object is being stored in a file. To better understand the transient keyword you must be knowledgeable about serialization concept in Java. Once you have completed reading the concept, let us talk about this keyword.

 Sometimes, there is a need that is mandatory to declare a member variable as transient because we know that not all objects can be serialized and only those which are of type Serializable can be i.e. the objects of the classes implementing the interface can be stored in a file.

For those members of the classes which cannot be serialized, their state cannot be stored in a file as it is i.e. they lack such capability and hence we might not need them to be stored. So, we'll make them transient.

Consider the following example which gives a better understand of what transient really does.

import java.util.*;
class Employee implements Serializable
int eno;
String ename;
transient Scanner s;  
    public Employee()
    s=new Scanner(;

    public void read()

    public void print()
    System.out.println(eno+"  "+ename);
class TransientExample
    public static void main(String args[])throws Exception

    Employee x=new Employee();;

    // Writing part..
    FileOutputStream fout=new FileOutputStream("emp.dat");
    ObjectOutputStream out=new ObjectOutputStream(fout);

    // Reading code..  
    FileInputStream    fin=new FileInputStream("emp.dat");
    ObjectInputStream oin=new ObjectInputStream(fin);
    Employee e=(Employee)oin.readObject();

    // Call print()


Sample Output

101  smith


java.util.Scanner class is not serializable i.e. it does not implement Serializable interface. So it's state cannot be stored as it is in a file. So it should be made transient so that it is not included while writing the object into a file.

What if the Scanner object is not made transient?

If the Scanner reference (here s) is not made transient, then you'll encounter the following exception.

Exception in thread "main" java.util.Scanner


        at TransientExample.main(

So you'll need to mention that s is not stored in the file. That's it.

The remaining code is however common and easy to fathom if you are familiar with the serialization tutorial. Drop a comment if you have any doubts related to the keyword transient.

Posted by at on

Tags: Java IO, Keywords,