It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "serialization" Watch "serialization" New topic


vini singh

Joined: Dec 04, 2008
Posts: 18

class TestSer
public static void main(String[] m)
SpecialSerial s=new SpecialSerial();
try{ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("myFile"));
System.out.println(++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("exec");}
class SpecialSerial implements Serializable
transient int y=7;
static int z=9;


output is:10 0 10 how as we know transient and static dont serialize therefore i think it should be 10 0 0

Rafael Angarita
Ranch Hand

Joined: Jan 09, 2009
Posts: 67
I think that the static member is not being serialized. The deserialized object doesn't have a "z" value. You can see it debugging the code.

But, since "z" is static and belongs to the class (not to the instances), its value is always there regardless new instances of the class;

Am I right?

Rafael Angarita.
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Yes you are right Rafael, static variable is not being written on file, not being read from file, it will not loose its value as it is class variable, it will not depend on instance objects being serialized here.

I agree. Here's the link:
subject: serialization
It's not a secret anymore!