This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
can you please explain the output of the above program
the output of the program is:
Before Serialization n1=10
Before Serialization n2=20
After Serialization n1=10
After Serialization n2=20
in the above program i have declared static int n1 instead of static if i will use transient int n1 then after serialization n1=0 and n2=20
but i have read that static and transient variables can not be serialized then in case of transient default value according to the data-type is printing but it is not in the case of static
please help me out from this situation
A static variable is part of a class, not part of any one object. if your class contain static variables it leads to problems some time.
if you are class contain one static variable it is serialized after the value of static variable value will be changed and again you are serialize the object. When you are going to deserialize of first object static variable value will not come before modified static value
so if you class including any static members, will already have been initialized.
static variable can not be serialized. static means bounded to class itself;i.e, not bounded to any of an object of class . serialization only persist object state(instance variable) into a file.
so, static variable can not be serialized while object get serialized. so what ever value you are getting for static variable from deserialization is from class, not from the particular instance.static value are initialized while class is loaded into JVM. dont access the static variable by using object reference;instead use class reference such ClassName.variablename
am write 2 programs based on your Number class if you are compile below 2 programs you can understand why static variables con't serialize
//serialize the objects
//de-serialization of object
if you are going to serialize and de-serialize in one class. at the time of de-serialization already initialized static variable values will be printed if you are going to serialize and de-serialize in different class you know the truth.