freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Transient Modifiers

   Transient modifier is the modifier applicable for only variables and we can’t apply for methods and classes.
   At the time of serialization, if we don’t want to save the values of a particular variable to meet security constraints then we should go for transient modifier.
  At the time of serialization JVM ignores the original value of transient variable and default value will be serialized.

import java.io.*;
import java.io.Serializable;
class Student implements Serializable
{ transient int id=100;
transient String name="ravi";
}
class Serializable1
{ public static void main(String args[])throws Exception
{ Student s1=new Student();
System.out.println("the stuent id is:"+s1.id);
System.out.println("the student name is:"+s1.name);
FileOutputStream fos=new FileOutputStream("a.txt",true);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(s1);
FileInputStream fis=new FileInputStream("a.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Student s=(Student)ois.readObject();
System.out.println("the stuent id is:"+s.id);
System.out.println("the student name is:"+s.name);
}
}

intput and output

output:100
ravi