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
- Static variables value can be stored while serializing if the same is provided while initialization.
- 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. 😛
very nice.
thank u …really useful for me
Great article!
Super…. its a nice site…
Hi ,
This website is very usefull to know exacting thing .
Regards,
Tirupathi
really wonderful explaine wid example
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
Correct…Static never get serialized as they are class level
Really article is very helpful.
Thanks a lot.
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.
Nice
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.
Very good article.
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?
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. 🙂
very nice..10q
true
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.
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.
Nice explaination..!!
Very Nice information, thanks for sharing.
Nice explanation!
Very well explained !!
Well explained… Thanks
Hi
Even if the variable inside the interface is not static or final, will it still retain the value of the variable
Nice
I got very clear scenarios.
Thanka a lot….!
very gd explanation, for easy understanding…
i was unaware about full concept of serialization. very good article. nice . thank a lot.
Nice article
Very Nice Explanation !!! Thanks.
Best article in Serialization.
what will happen if during de serialization process someone changed our serialized class
Hi Satish,
If you go through all 3 sections in Serialization chapter you will get to know what will happen in this condition and other condition that might arise.
look for below url and other chapter in same series.
http://javabeginnerstutorial.com/core-java-tutorial/java-serialization-concept-example/
Regards
Thanks!
Very helpful and great Article
Good Article. Keep it up buddy 🙂
Great Article
salute sir … awesome
Thank you pankaj
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.
Nice Article
cleand and neat explanation!!!
very nice