wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static variables are never saved during Serialization, yet my code seems to do the opposite 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 "Static variables are never saved during Serialization, yet my code seems to do the opposite" Watch "Static variables are never saved during Serialization, yet my code seems to do the opposite" New topic
Author

Static variables are never saved during Serialization, yet my code seems to do the opposite

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Hello,

I just finished Chapter 6 of Sierra/Bates, and now I am on Chapter 7 that begins its discussion with Hashing. I modified the following code, based on Chapter 7:



My output is:

45 50
0 50



I would think that the output is:

45 50
0 5


because in deserialization, the constructor is called, and y gets it's static value of 5. Please explain.

Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
The constructor is not called for your 'Serializable' class. If the JVM must reload
the class, however, the statics will revert to their initialized values. Otherwise, if
you serialize and then immediately deserialize, static values are untouched.

Jim ... ...


BEE MBA PMP SCJP-6
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
When recreating an instance from a serialized object, the constructor with no parameters is used. Because you did not specify this constructor, the compiler creates one for you.

EDIT: I tried my own test (creating a constructor with no parameters) and found I was wrong. Looks like it's back to reading the book for me :-)

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Where can I find an example program that demonstrates static variables reverting to their original values after class is de-serialized. Or better yet, how can I modify the code I posted to perform this action. Please guide.
Unmesh Chowdhury
Ranch Hand

Joined: Jun 20, 2010
Posts: 45
Hi Sandra, Jim Hoglund is correct. You can decompose your code into three parts as follows:

1st Part:

2nd Part:
(As separate compilation unit)

3rd Part:
(As individual CU)


I think, you can experiment now.


M.Sc. in CS, OCPJP6 93%
Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Thank you for the code to experiment with, now I understand better!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Static variables are never saved during Serialization, yet my code seems to do the opposite