Transient variable:
A variable declared with transient keyword is a transient variable. It is used in serialization process to provide flexibility for excluding some variables from serialization process. A variable declared with transient keyword will not be serialized.
Example:
TransientExample.java
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * This program is used to show that transient variables * are not saved in serialization process. * @author w3schools */ class Student implements Serializable{ //Serial Version UID. private static final long serialVersionUID = 1L; String name; transient String className; String rollNo; //Constructor. Student(String name, String className, String rollNo){ this.name = name; this.className = className; this.rollNo = rollNo; } } class Test{ //Write serialized object into objectoutputstream. public void objectSerialization(Student stu){ try{ //Creating FileOutputStream object. FileOutputStream fos = new FileOutputStream("F:\\New folder\\studentTransient.ser"); //Creating ObjectOutputStream object. ObjectOutputStream oos = new ObjectOutputStream(fos); //write object. oos.writeObject(stu); //close streams. oos.close(); fos.close(); System.out.println("Serialized data is saved in " + "F:\\New folder\\studentTransient.ser"); }catch(IOException e){ System.out.println(e); } } //Deserialize a serialize object. public void objectDeSerialization(){ try{ Student stu = null; //Creating FileOutputStream object. FileInputStream fis = new FileInputStream("F:\\New folder\\studentTransient.ser"); //Creating ObjectOutputStream object. ObjectInputStream ois = new ObjectInputStream(fis); //write object. stu = (Student) ois.readObject(); //close streams. ois.close(); fis.close(); System.out.println("Name = " + stu.name); System.out.println("Class Name = " + stu.className); System.out.println("RollNo = " + stu.rollNo); }catch(Exception e){ System.out.println(e); } } } public class TransientExample { public static void main(String args[]){ //Creating Student object. Student stu = new Student("Parmander", "MCA", "MCA/07/27"); //Creating Test object. Test obj = new Test(); //Method call. obj.objectSerialization(stu); obj.objectDeSerialization(); } } |
Output:
Serialized data is saved in F:\New folder\studentTransient.ser Name = Parmander Class Name = null RollNo = MCA/07/27 |
Which types of variables are not serialized during Java Serialization?
Static and transient variables are not serialized during Java Serialization. As static are associated to the class and not to an object hence they are not the part of the state of object so they are not saved during Java Serialization process.
Next Topic: Collection framework in java.
Previous Topic: Serialization in java with example.