Which kind of variables are not serialized during Java Serialization?

Now we will discuss how static and transient variables behave during serialization. The static members belongs to the class not to the object and the concept of serialization works for object’s current state only that’s why only the data of objects will be serialized and static members will be ignored during serialization.

The variables marked as transient will not be serialized because the use of transient keyword before a variable is the indication to the JVM that this variable is not the part of persistent state of object.

Here is an example of serialization in which static and transient variables get ignored during serialization. While deserialization the value of static variables will be loaded from class and the value of transient variables will be initialized with defaults values.

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

class TestSerialization{

	public static void main(String... m){
		try(FileOutputStream fos = new FileOutputStream("D:/test.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos)) {
			A a = new A();
		catch(IOException e) {

		try(FileInputStream fis = new FileInputStream("D:/test.ser");
			ObjectInputStream oos = new ObjectInputStream(fis)) {
			A a = (A)oos.readObject();
			System.out.println("Value of i = " + a.i);
			System.out.println("Value of j = " + a.j);
			System.out.println("Value of k = " + a.k);
		catch(IOException | ClassNotFoundException e) {

class A implements Serializable{

	public int i = 10;
	public static int j = 10;
	public transient int k = 10;

	public void changeData(int t){
		i = j = k = t;


Value of i = 20
Value of j = 30
Value of k = 0

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com