package p1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SerializationCheck {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
SingletonCompanyCEO s1 = SingletonCompanyCEO.getSingleObject();
SingletonCompanyCEO s2 = SingletonCompanyCEO.getSingleObject();
System.out.println("s1==s2:"+(s1==s2));
ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream("file.txt"));
obs.writeObject(s1);
//first read from file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.txt"));
SingletonCompanyCEO ceo = (SingletonCompanyCEO)ois.readObject();
//second read from file
ois = new ObjectInputStream(new FileInputStream("file.txt"));
SingletonCompanyCEO ceo1 = (SingletonCompanyCEO)ois.readObject();
System.out.println("ceo==ceo1:"+(ceo==ceo1)+" (read from file ie. de-serialized )");
System.out.println(ceo1);
}
}
class SingletonCompanyCEO implements Serializable
{
public void setName(String name){
this.name = name;
}
public Object readResolve() throws ObjectStreamException {
return singleObject;
}
private static final long serialVersionUID = 1L;
private transient int age = 55; // age should set to zero by default as age is transient. But it is not happening, any reason?
private String name ="Amit";
float salary = 0f;
private static SingletonCompanyCEO singleObject;
private SingletonCompanyCEO()
{
if(singleObject!=null)
{
throw new IllegalStateException();
}
}
public static SingletonCompanyCEO getSingleObject()
{
if(singleObject==null)
{
singleObject = new SingletonCompanyCEO();
}
return singleObject;
}
public String toString()
{
return name+" is CEO of the company and his age is "+
age+"(here 'age' is transient variable and did not set to zero while serialization)";
}
}
copy and paste this code in eclipse editor.
What is the reason where 'age' transient
variable is not set to zero by default while serialization?
Serialization says that transient and static variable are set to zero(or default values) while serialization.
After de-serialization I am getting age = 55
instead of age = 0
.
There must be reason behind this in JLS. What is it?