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
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 serializedIn 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 :
Syntax :
transient data-type variable-name;
Example :
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 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; this.address=address; } 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 o.writeObject(ob); o.close(); ObjectInputStream in=new ObjectInputStream(new FileInputStream("Demo")); Demo1 ob1=(Demo1)in.readObject(); //System.out.println(ob1); ob1.display(); } }
Output : After compiling and executing the program.
Ads