How to use transient keyword in Java with example

In this article, we will learn what is the transient keyword and how to use it in Java. Also, we will try to understand why we use it.

What is the transient keyword?

Transient is a keyword which we use in serialization, this keyword is used to indicate JVM which that field which has transient keyword is not part of the serialization, which means after deserialization the value of the transient field will change with a default value of that field.

How to use the transient keyword in Java?

During modifying the variable first write access modifiers after that transient keyword also we can use another way which first writes transient keyword after that access modifier, you can see in example better.

public transient String name;
 transient public String name;

Example:

import java.io.*;

public class Codespeedy {
  
    public static void main(String args[]) throws Exception
    {  
    Test test=new Test("ali",20,12);
    String fileName="abc.txt";
    
    
        FileOutputStream file=new FileOutputStream(fileName);
        ObjectOutputStream oos=new ObjectOutputStream(file);
        
        oos.writeObject(test);          // object serialized
        oos.close();
        file.close();
        System.out.println("value befor Deserialization"):
        System.out.println(test.a+"   "+test.name+"     "+test.age);
        
        test=null;
        
         FileInputStream file1 = new FileInputStream(fileName);                                         
         ObjectInputStream ois = new ObjectInputStream(file1); 
         test= (Test)ois.readObject();
                                           // object Deserialized
         file1.close();
         ois.close();
         System.out.println("value after Deserialization");
         System.out.println(test.a+"   "+test.name+"     "+test.age);
    }
}

class Test implements Serializable
{ 
    transient  int a;
    int age;
    public transient String name;
    public Test(String name,int a,int age)
    {
        this.name=name;
        this.a=a;
        this.age=age;
    }
}

Output:

value befor Deserialization
20 ali 12
value after Deserialization
0 null 12

As you can see two variables are transient after the Deserialization value of that two variable became the default value of int is zero and the value of Object(String) is null.

Also, read:

 

Why use it?

If we want to prevent a part of an object from serialization we should use this keyword. When we want to serialize one object that object will change to byte-stream after deserializing it will change from byte-stream to object during this all value is the same as initial at the first but just transient part is changed to the default value.

Leave a Reply

Your email address will not be published. Required fields are marked *