Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confusion regarding serialization with static and transient variable

 
kapilg gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;

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

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

ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));
SpecialSerial s2= (SpecialSerial)is.readObject();
is.close();
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
author
Marshal
Pie
Posts: 21407
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).

Yours,
A.P.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic