This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Serialization " Watch "Serialization " New topic


Laloo Bond

Joined: Jun 06, 2008
Posts: 5
Static variables cannot be serialized, as serialization is meant for only objects and not for class.

Now my doubt is, if we use the static variables in the class, and while serializing the object , the value of static variable may be different and when deserializing the object the static variable may be different.

How it will restore the correct value for the object which is deserialized?

Do we have to serialise it manually ?How it will work?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42954
There is no single "correct" value for static fields. Serialization simply ignores them. So if an object is deserialized, the static fields of that class remain what they were before the deserialization. If you want fields that can change on a per-object basis, they can't be static.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3370

That's true. As Ulf said, the static values never come into picture of the serialization at all. They are treated as if the "instance variables marked as transient"!

So, no need to bother!

Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Henry Wong

Joined: Sep 28, 2004
Posts: 19343

Do we have to serialise it manually ?How it will work?

If you really want to serialize/deserialize static variables, then you can implement the readObject() and writeObject() methods for the class. (technically, it is not "override" since these are private methods).

However, keep in mind, that when you deserialize, you will be changing a static variable -- which is a variable used by every object of that class type.


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

Joined: Nov 08, 2007
Posts: 457
you can customize serialization (as stated above),

but what would happen if you unserialized two different objects that both tried to write to the static value? non-deterministic behavior.


you should question the design and use of the static variable

Bill Shirley - bshirley -
if (Posts < 30) JavaRanchFAQ);
Consider Paul's rocket mass heater.
subject: Serialization