All for Joomla All for Webmasters

Java Transient Keyword

Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

Let’s take an example, I have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but I don’t want to serialize one value, e.g. age then we can declare the age data member as transient.

Example of Java Transient Keyword

In this example, we have created the two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized.

If you deserialize the object, you will get the default value for transient variable.

Let’s create a class with transient variable.

  1. import;
  2. public class Student implements Serializable{
  3.  int id;
  4.  String name;
  5.  transient int age;//Now it will not be serialized
  6.  public Student(int id, String name,int age) {
  7. = id;
  8. = name;
  9.   this.age=age;
  10.  }
  11. }

Now write the code to serialize the object.

  1. import*;
  2. class PersistExample{
  3.  public static void main(String args[])throws Exception{
  4.   Student s1 =new Student(211,“ravi”,22);//creating object
  5.   //writing object into file
  6.   FileOutputStream f=new FileOutputStream(“f.txt”);
  7.   ObjectOutputStream out=new ObjectOutputStream(f);
  8.   out.writeObject(s1);
  9.   out.flush();
  10.   out.close();
  11.   f.close();
  12.   System.out.println(“success”);
  13.  }
  14. }



Now write the code for deserialization.

  1. import*;
  2. class DePersist{
  3.  public static void main(String args[])throws Exception{
  4.   ObjectInputStream in=new ObjectInputStream(new FileInputStream(“f.txt”));
  5.   Student s=(Student)in.readObject();
  6.   System.out.println(” “” “+s.age);
  7.   in.close();
  8.  }
  9. }
211 ravi 0

As you can see, printing age of the student returns 0 because value of age was not serialized.

submit to reddit

Leave a Reply