File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes confusion regarding serialization with static and transient variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "confusion regarding serialization with static and transient variable" Watch "confusion regarding serialization with static and transient variable" New topic

confusion regarding serialization with static and transient variable

kapilg gupta

Joined: Jun 14, 2006
Posts: 10

public class TestSer{public static void main (String[] args)
SpecialSerial s=new SpecialSerial();
ObjectOutputStream os = new ObjectOutputStream (new FileOutputStream("myFile"));

System.out.println(s.y + " " +s.z);

ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));
SpecialSerial s2= (SpecialSerial)is.readObject();
System.out.println(s2.y + " " +s2.z);
catch(Exception x) { System.out.println("exc");}
class SpecialSerial implements Serializable
transient int y=7;
static int z =9;

Output:-7 9
0 9
I know that static and transient variable are not serialized then how come after deserialization static varible holds its value whereas transient variable is 0.
please explain
Henry Wong

Joined: Sep 28, 2004
Posts: 19932

Remember that there is only one copy of static variables for all instances of that class -- or basically, the value didn't change!

Try this... After you serialize out to the file, but before you deserialize the file, change the static variable to something else. You'll notice that it will not change back after deserialization.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
G'day mates!

I'll split your question into two:
Q1: Why is the transient variable zero after deserialization?
To serialize an object, the marker interface "Serializable" is implemented. One consequence is, that the constructor of your class "SpecialSerial" will not run in the deserialization process. And so there will be no seven assignet to . The nontransient variables will get their value during deserialization while the transient varables will get a default value. Zero in case of int primitives.

Q2: Why is the static variable (still) nine?
Henry already answered this but anyway: This has nothing to do with serialization. You serialize objects only. But static fields belong to the class. And when you set it will be nine for this class and all its objects for all times. Or until you assign a different value (through any of its objects or through the class itself).


all events occur in real time
I agree. Here's the link:
subject: confusion regarding serialization with static and transient variable
jQuery in Action, 3rd edition