Java – Transient keyword with static variable in Serialization

In this article, we will discuss what happens to static data member when transient keyword or modifier applied during Serialization process

This is one of the tricky questions asked in Java interview

Q) What happens in serialization process, if we declare static data member with transient keyword ?

  • The answer is very simple, only instance variables will be participated in Serialization process
  • static variables doesn’t participate in Serialization process
  • Reason : static variable isn’t part of Object’s state
  • So, by declaring static data member with transient doesn’t have any impact
  • There won’t be any compile-time or run-time error

1. transient keyword

  • Transient keyword or modifier is applicable only for variables
  • We can stop persisting specific variable, by declaring transient keyword
  • During serialization, JVM ignores the original value of transient variable and saves default value to file
  • Examples: Customer SSN or password need not to be stored. Hence, it’s a good practice to declare those variables as transient
  • So whenever we encounter transient keyword, it means that not to serialize

2. static variable

  • A variable declared with static modifier is known as static variable
  • Alternatively it is referred as class variable as it belongs to class rather to any specific instance
  • Static variable shared among every instance like for example organization name of the employee
  • It should be used whenever there is common property for all objects of that class
  • Static variables can be accessed directly by class name or interface name instead of creating an instance and then accessing
  • Static variables can be accessed from static and non-static methods/blocks using class name or interface name
  • Memory allocation for static variables happens at the time of class loading by JVM

3. Demo example on Transient keyword with static data member

  • For objects to participate in serialization & de-serialization process, corresponding class should implement java.io.Serializable interface
  • Otherwise NotSerializableException will be thrown

Step 1: Create POJO which implements java.io.Serializable interface

  • In Customer POJO, there are 4 member variables
  • customerSSN declared with transient keyword
  • also 1 static data member called customerCount initialized to 2
  • transient customerSSN –> default value will be saved instead of original value
  • transient static customerCount –> won’t participate in serialization

Customer.java

package in.bench.resources.serialization;

import java.io.Serializable;

public class Customer implements Serializable {

	// static data member
	static int customerCount = 2;

	// member variables
	int customerId;
	String customerName;
	int customerAge;
	transient int customerSSN; // transient

	// 4-arg parametrized constructor
	public Customer(int customerId, String customerName,
			int customerAge, int customerSSN) {
		super();
		this.customerId = customerId;
		this.customerName = customerName;
		this.customerAge = customerAge;
		this.customerAge = customerAge;
	}

	// overriding toString() method
	@Override
	public String toString() {
		return "Customer ["
				+ "customerId=" + customerId
				+ ", customerName=" + customerName
				+ ", customerAge=" + customerAge
				+ ", customerSSN=" + customerSSN
				+ ", customerCount=" + customerCount
				+ "]";
	}
}

Step 2: Main program to demonstrate serialization/de-serialization

  • To Serialize any Object, we can use ObjectOutputStream & FileOutputStream to write/save to the file (in binary format)
  • To De-Serialize any Object, we can use ObjectInputStream & FileInputStream to read/restore from file (which is in binary format) into Java heap memory

TransientWithStaticDemo.java

package in.bench.resources.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TransientWithStaticDemo {

	public static void main(String[] args) {

		// create an customer instance using 4-arg constructor
		Customer serializeCustomer =
				new Customer(103, "AK", 21, 112563);

		// creating output stream variables
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;

		// creating input stream variables
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		// creating customer object reference
		// to hold values after de-serialization
		Customer deSerializeCustomer = null;

		try {
			// for writing or saving binary data
			fos = new FileOutputStream("Customer.ser");

			// converting java-object to binary-format
			oos = new ObjectOutputStream(fos);

			// writing or saving customer object's value to stream
			oos.writeObject(serializeCustomer);
			oos.flush();
			oos.close();

			System.out.println("Serialization success: Customer"
					+ " object saved to Customer.ser file\n");

			// reading binary data
			fis = new FileInputStream("Customer.ser");

			// converting binary-data to java-object
			ois = new ObjectInputStream(fis);

			// reading object's value and casting to Customer class
			deSerializeCustomer = (Customer) ois.readObject();
			ois.close();

			System.out.println("De-Serialization success: Customer"
					+ " object de-serialized from Customer.ser file\n");
		}
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		}
		catch (ClassNotFoundException ccex) {
			ccex.printStackTrace();
		}

		// printing customer object to console using toString() method
		System.out.println("Printing customer values from "
				+ "de-serialized object... \n" + deSerializeCustomer);
	}
}

Output:

Serialization success: Customer object saved to Customer.ser file

De-Serialization success: Customer object de-serialized
from Customer.ser file

Printing customer values from de-serialized object...
Customer [customerId=103, customerName=AK, customerAge=21, customerSSN=0,
customerCount=2]

Explanation:

During Serialization process,

  • In above Customer POJO, customerSSN declared as transient so therefore this is ignored by JVM
  • Only Object’s state is persisted to file (i.e.; only instance variables)
  • Static data member aren’t part of Object’s state, so this won’t be considered
  • When we de-serialize, all instance variables without transient keyword will be restored
  • But static data member doesn’t participated in serialization neither its gets persisted nor restored back from file

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Transient keyword with final variable in Serialization
Java - Transient keyword with Serialization