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.


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.

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) { = id; = name;

See Also:

Serialization Example: with the static keyword


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

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



Employee object Serialize Successfully

Deserialization Example: with the static keyword


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 :""\nName: ""\nAge: "+e.age);



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.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your 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