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 different scope but people use to ask me this question every time so i am mentioning it here. For previous Serialization articles click here(Pat I) and here(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 state of a variable. You have to mark that variable as Transient. Environment will know that this variable should be ignored and will not save the value of same.

Note*: Even concept is completely different and 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 value of companyName, companyCEO has been saved but not of address. Also check the saved value of these variable.

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 variabls value is saved even when it is transient. Because static modifier change the behavior of this variable.

Bullet Point

  1. Static variables value can be stored while serializing if the same is provided while initialization.
  2. If variable is defined as Static and Transient both, than static modifier will govern the behavior of variable and not Transient.

 

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

Series Navigation<< Java serialization concept and Example Part IIWhat is the use of serialVersionUID >>
By | 2013-12-29T07:01:22+00:00 December 29th, 2013|Core Java|41 Comments

About the Author:

41 Comments

  1. ganesh January 20, 2014 at 6:35 am - Reply

    very nice.

  2. Anu May 11, 2014 at 12:42 pm - Reply

    thank u …really useful for me

  3. Mohita May 16, 2014 at 10:05 am - Reply

    Great article!

  4. Chaitanya V June 15, 2014 at 7:31 am - Reply

    Super…. its a nice site…

  5. Tirupathi Reddy July 4, 2014 at 5:58 am - Reply

    Hi ,
    This website is very usefull to know exacting thing .

    Regards,
    Tirupathi

  6. sandeep August 4, 2014 at 4:57 pm - Reply

    really wonderful explaine wid example

  7. Hieu Tran August 14, 2014 at 8:05 am - Reply

    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

    • Vinayak August 15, 2016 at 2:25 pm - Reply

      Correct…Static never get serialized as they are class level

  8. sirisha September 18, 2014 at 5:12 pm - Reply

    Really article is very helpful.
    Thanks a lot.

  9. Sarika November 7, 2014 at 7:53 am - Reply

    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.

  10. Ravi November 14, 2014 at 5:34 pm - Reply

    Nice

  11. Anurag January 2, 2015 at 1:02 pm - Reply

    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.

  12. Siva Sankar January 12, 2015 at 6:14 am - Reply

    Very good article.

  13. tamkanat January 23, 2015 at 6:01 am - Reply

    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?

    • Vivekanand Gautam January 24, 2015 at 4:52 am - Reply

      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. ๐Ÿ™‚

      • venkataramareddy March 29, 2015 at 6:29 pm - Reply

        very nice..10q

      • VicXj April 1, 2017 at 2:15 pm - Reply

        true

  14. Naveen Goel February 3, 2015 at 5:07 pm - Reply

    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.

  15. Naveen Goel February 3, 2015 at 5:09 pm - Reply

    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.

  16. Shailesh March 18, 2015 at 5:20 pm - Reply

    Nice explaination..!!

  17. Rafeeq Mullan April 21, 2015 at 10:13 am - Reply

    Very Nice information, thanks for sharing.

  18. Shilpa Khare July 24, 2015 at 10:18 am - Reply

    Nice explanation!

  19. Bhaskar August 12, 2015 at 2:01 pm - Reply

    Very well explained !!

  20. Namita August 13, 2015 at 7:20 am - Reply

    Well explained… Thanks

  21. Balapoorna August 25, 2015 at 1:25 pm - Reply

    Hi

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

  22. Asanthine November 4, 2015 at 9:56 pm - Reply

    Nice

  23. praveen December 13, 2015 at 2:03 am - Reply

    I got very clear scenarios.
    Thanka a lot….!

  24. yaswanth kumar A January 18, 2016 at 5:44 am - Reply

    very gd explanation, for easy understanding…

  25. ravindra April 1, 2016 at 6:58 am - Reply

    i was unaware about full concept of serialization. very good article. nice . thank a lot.

  26. Guhan April 19, 2016 at 8:41 am - Reply

    Nice article

  27. Amit May 11, 2016 at 8:33 pm - Reply

    Very Nice Explanation !!! Thanks.

  28. Gaurav May 20, 2016 at 7:43 am - Reply

    Best article in Serialization.

  29. Satish Chandra May 28, 2016 at 7:57 pm - Reply

    what will happen if during de serialization process someone changed our serialized class

  30. Anshu May 29, 2016 at 7:19 am - Reply

    Thanks!

    Very helpful and great Article

  31. Robo June 19, 2016 at 5:44 pm - Reply

    Good Article. Keep it up buddy ๐Ÿ™‚

  32. amit July 22, 2016 at 10:30 am - Reply

    Great Article

  33. pankaj September 13, 2016 at 1:38 pm - Reply

    salute sir … awesome

  34. Aruna January 31, 2017 at 10:42 pm - Reply

    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.

  35. vikash February 9, 2017 at 2:37 pm - Reply

    Nice Article

Leave A Comment