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. ๐Ÿ˜›

59 Comments Transient vs Static variable java

  1. 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.

    Reply
  2. EJP

    ‘Static variables value can be stored while serializing if the same is provided while initialization’ is incorrect, and contradicts the earlier statement that static variables are not serialized, which is correct.

    ‘If variable is defined as Static and Transient both, than static modifier will govern the behavior of variable and not Transient’ is meaningless, as from the point of view of Serialization they both have the same effect.

    Reply
    1. Vivekanand

      These statements are correct. Please pay attention to the code. Meanwhile, I have made changes to the article to make it more clear. What I meant by saying that.

      Reply
  3. Aruna

    Hi, Just to add one info. I have come across with this question. What to do if I want to avoid SubClass serialization. Then override writeObject Method and throw NotSerializableException.

    Reply
  4. Balapoorna

    Hi

    Even if the variable inside the interface is not static or final, will it still retain the value of the variable

    Reply
  5. Naveen Goel

    Hi Vivekananda’s,

    In case of interface data is not serialized because in interfaces by default all fields are final and as you already explained final fields govern behavior of variables as static.

    Reply
  6. Naveen Goel

    Hiii
    Do you think there might be some security leak of data while serialization because your data is freely moves into your class and also the outside of the class. So what’s better approach to safe guard data is Inner class concept is good.

    Reply
  7. tamkanat

    hi,
    very nice information.thanks for the effort.
    If u dont mind, can u tell y u dint qualified.
    wat did they asked u in interview that u couldnt answer?

    Reply
    1. Vivekanand Gautam

      Hi Tamkant,

      Thanks for your nice word. I am sorry but i donโ€™t remember the questions. After all these years i can say
      qualifying in an interview is not only dependent on your knowledge but also on Interviewers knowledge.
      I have taken so many interviews my self. And you can not judge someone in 30 min.
      Better we only concentrate on our knowledge and be confident. Someone will understand you.
      And you will qualify the interview someday. ๐Ÿ™‚

      Reply
  8. Anurag

    Similarly final variables are also not serialized and they are picked from class as soon the class loads itself. You can verify the serialized value in a file and you will not found any final or static variable content there.

    Reply
  9. Sarika

    The static variable values are printed because they are accessed along with the class. Static variables can be accessed by classname.staticvariable.
    companyname, companyCEO, education are all static variable values and are printed because they called as classname.variable.

    Reply
  10. Hieu Tran

    The static variable(education) aren’t saved, because it is a static variable.
    In this case, the line System.out.println(“Education: “+emp.education); printed out the value bevause education’s value is loaded from class, not from serialized object

    Reply

Leave 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.