Scroll to top

Transient vs Static variable java

Here I will show you what is the difference between Static and Transient. In any way, these two things are completely different with the different scope but people use to ask me this question lot of time. Here in this article, I will try to explain it. Fore previous articles you can click here(Part I) and here for (Part II).

Static Variable

Static variables belong to a class and not to any individual instance. The concept of serialization is concerned with the object’s current state. Only data associated with a specific instance of a class is serialized, therefore static member fields are ignored during serialization.

Transient Variable

While serialization if you don’t want to save the state of a variable. You have to mark that variable as Transient. The environment will know that this variable should be ignored and will not save the value of same.

Even concept is completely different and the reason behind not saving is different still people get confused about the existence of both. As in both the case variables value will not get saved.

Difference between these two

Source code: Pay attention to every single code change.

Employee.java

package com.jbt;

import java.io.Serializable;

public class Employee extends superEmployee {
	public String firstName;
	private static final long serialVersionUID = 5462223600l;
}

class superEmployee implements Serializable{
	public String lastName;
	static  String companyName;
	transient  String address;
	static transient String companyCEO;
}

SerializaitonClass.java

package com.jbt;

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

public class SerializaitonClass {

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.firstName = "Vivekanand";
		emp.lastName = "Gautam";
		emp.companyName = "JBT";
		//Below part needs to be removed in case address field is made final
		emp.address = "MUM";
		emp.companyCEO = "ME CEO";

		try {
			FileOutputStream fileOut = new FileOutputStream("./employee.txt");
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(emp);
			out.close();
			fileOut.close();
			System.out.printf("Serialized data is saved in ./employee.txt file");
		} catch (IOException i) {
			i.printStackTrace();
		}
	}
}

DeserializationClass.java

package com.jbt;

import java.io.*;

public class DeserializationClass {
	public static void main(String[] args) {
		Employee emp = null;
		try {
			FileInputStream fileIn = new FileInputStream("./employee.txt");
			ObjectInputStream in = new ObjectInputStream(fileIn);
			emp = (Employee) in.readObject();
			in.close();
			fileIn.close();
		} catch (IOException i) {
			i.printStackTrace();
			return;
		} catch (ClassNotFoundException c) {
			System.out.println("Employee class not found");
			c.printStackTrace();
			return;
		}
		System.out.println("Deserializing Employee...");
		System.out.println("First Name of Employee: " + emp.firstName);
		System.out.println("Last Name of Employee: " + emp.lastName);
		System.out.println("Company Name: "+emp.companyName);
		System.out.println("Company CEO: "+emp.companyCEO);
		System.out.println("Company Address: "+emp.address);
	}
}

First Execute “SerializaitonClass” and you will get below output.

Serialized data is saved in ./employee.txt file

Second, execute “DeserializationClass” and you will get below output

Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: null
Company CEO: null
Company Address: null

As you can see from output only last name value has been saved. Neither Static nor Transient variables value has been saved.

Now I will change the code a little bit and see what happens.

Employee.java

package com.jbt;

import java.io.Serializable;

public class Employee extends superEmployee {
	public String firstName;
	private static final long serialVersionUID = 5462223600l;
}

class superEmployee implements Serializable {
	public String lastName;
	/*
	 * Here i am providing the value of company name,companyCEO and address
	 * while defining these variables.
	 */
	static String companyName = "TATA";
	transient String address = "DEL";
	static transient String companyCEO = "Jayshree";
}

Again execute the same code and see the output

Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: TATA
Company CEO: Jayshree
Company Address: null

See the output very carefully. Here the value of companyName, companyCEO has been saved but not of address. Also, check the saved value of these variables.

Company Name: TATA
Company CEO: Jayshree

In both, the case value stored here are taken from class(Employee class) and not from Object(emp object). Also, companyCEO variable value is saved even when it is transient. Because static modifier changes the behavior of this variable.

Bullet Point

  1. A static variable cannot be serialized.
  2. While de-serializing a value can be available for Static variables if the same is provided while initialization of the base class.
    • It doesn’t mean that static variable will be serialized. It only means that the static variable will be initialized with the same value, it is assigned while loading the class(Which is TATA in this case). If classes are not loaded before(New JVM). Please pay attention to example code.
    • In case class is already loaded in JVM and static variable value has been changed then the changed value will be displayed.
  3. If the variable is defined as Static and Transient both than static modifier will govern the behavior of variable and not Transient.
    • Static and Transient is different. In cases, their behavior looks the same, but not always. If you have assigned a value to a variable while loading the class then that value will be assigned to the static variable while de-serializing the class but not to transient. So if you are using both of these modifiers with a variable, then in that sense, I am saying that static will take precedent to transient.
  4. Transient variables value will not be saved. Also, it can not be assigned any value while de-serialization process. Which is different from static behavior.

 

Final modifier effect on Serialization

To see the effect of Final modifier I am again changing the code of Employee class.

Employee.java

package com.jbt;

import java.io.Serializable;

public class Employee extends superEmployee {
	public String firstName;
	private static final long serialVersionUID = 5462223600l;
}

class superEmployee implements Serializable {
	public String lastName;
	/*
	 * Here i am providing the value of company name,companyCEO and address
	 * while defining these variables.
	 * I am making address as final here
	 */
	static String companyName = "TATA";
	transient final String address = "DEL";
	static transient String companyCEO = "Jayshree";
}

Again execute the code and see the difference. Output for the above code would be

Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: TATA
Company CEO: Jayshree
Company Address: DEL

As you can see now address fields is also saved while serialization because it is now Final.

Interface and Final

I have seen a scenario when you can serialize variables inside an Interface which is not serialized.

Employee.java

package com.jbt;

import java.io.Serializable;

public class Employee extends superEmployee implements variableConstant{
	public String firstName;
	private static final long serialVersionUID = 5462223600l;
}

class superEmployee implements Serializable {
	public String lastName;
	/*
	 * Here i am providing the value of company name,companyCEO and address
	 * while defining these variables.
	 * I am making address as final here
	 */
	static String companyName = "TATA";
	transient final String address = "DEL";
	static transient String companyCEO = "Jayshree";
}

interface variableConstant  {
	public static final String education = "MCA";

}

DeserializationClass.java

package com.jbt;

import java.io.*;

public class DeserializationClass {
	public static void main(String[] args) {
		Employee emp = null;
		try {
			FileInputStream fileIn = new FileInputStream("./employee.txt");
			ObjectInputStream in = new ObjectInputStream(fileIn);
			emp = (Employee) in.readObject();
			in.close();
			fileIn.close();
		} catch (IOException i) {
			i.printStackTrace();
			return;
		} catch (ClassNotFoundException c) {
			System.out.println("Employee class not found");
			c.printStackTrace();
			return;
		}
		System.out.println("Deserializing Employee...");
		System.out.println("First Name of Employee: " + emp.firstName);
		System.out.println("Last Name of Employee: " + emp.lastName);
		System.out.println("Company Name: "+emp.companyName);
		System.out.println("Company CEO: "+emp.companyCEO);
		System.out.println("Company Address: "+emp.address);
		System.out.println("Education: "+emp.education);
	}
}

Execute the above code and see the output.

Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: TATA
Company CEO: Jayshree
Company Address: DEL
Education: MCA

Here you can see that education’s value is saved. This value is part of an Interface. But as this is constant hence it is saved while serialization.

I think I have covered all possible scenarios. Do let me know in case any particular scenario is not covered in this article. Feel free to say me hi,  if you like this article. And yes I didn’t qualify for the interview. 😛

Author avatar
JBT
https://javabeginnerstutorial.com/

58 comments

  1. Supriya

    Really Helpful Article! Thank you!

  2. Sayeed

    Very much inoformative article. Thanks for sharing.

  3. Arun

    Very useful… Love you Bro

  4. malashri

    super! very informative one.

  5. Bhanu Prakash Alapati

    Omg! this is really amazing. I could just hold of everything in just one place. Keep posting more stuff like which has different scenarios. I would suggest you post more on multithreading and synchronize methods.

Post a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.