Java: static Serialization and Deserialization Examples


The variable declares with static keyword are known as class variables these variables will not serialize when doing serialization for objects of the class.

Note: Fields declare as transient also not serialize.

Pre-requisite:

For Example: In Employee Class fields age is declared with the keyword static. When you serialize the object of class Employee then values of age will not serialize and time of deserialization initialize with default value as per type.

import java.io.Serializable;
public class Employee implements Serializable{
 int id;
 String name;
//This field will not be serialized
 static int age;
 public Employee(int id, String name,int age) {
  this.id = id;
  this.name = name;
  this.age=age;
 }
}

See Also:

Serialization Example: with the static keyword

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializationWithStaticExample {

	public static void main(String args[]) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		// writing object into employee file
		FileOutputStream f = new FileOutputStream("employee.txt");
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();

		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

}

Output


Employee object Serialize Successfully

Deserialization Example: with the static keyword

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationWithStaticExample {

	public static void main(String[] args) throws Exception {
		 //Read object stream from file
		  ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));
		 //Deserialize object stream to employee object
		  Employee e=(Employee)in.readObject();
		  System.out.println("Employee Detail :");
		  System.out.println("Id :"+e.id+"\nName: "+e.name+"\nAge: "+e.age);
		  in.close();  

	}
}

Output


Employee Detail :
Id :111
Name: Saurabh
Age: 0

As you can see, the printing age of the employee returns 0 as default initialize value for int type because the value of age was not serialized.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s