Can we serialize static variables in Java?

Java 8Object Oriented ProgrammingProgramming

In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).

But, static variables belong to class therefore, you cannot serialize static variables in Java. Still if you try to do so, the program gets compiled successfully but it raises an exception at the time of execution.

In the following java program, the class Student has a static variable and we are trying to serialize and desterilize its object in the another class named ExampleSerialize.

Example

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
   private static String name;
   public Student(String name){
      this.name = name;
   }
   public static String getName() {
      return name;
   }
   public static void setAge(String name) {
      Student.name = name;
   }
}
public class ExampleSerialize{
   public static void main(String args[]) throws Exception{
      Student std1 = new Student("Krishna", 30);
      FileOutputStream fos = new FileOutputStream("e:\\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std1);

      FileInputStream fis = new FileInputStream("e:\\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student std2 = (Student) ois.readObject();
      System.out.println(std2.getName());
   }
}

Run time error

This program gets executed successfully but, while running you will get a run time exception as shown below −

Exception in thread "main" java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to java.io.ObjectOutput
at sample.TestSerialize.main(TestSerialize.java:31)
raja
Published on 05-Jul-2019 07:38:38
Advertisements