Serialization
Serialization
SERIALIZATION :
Create object of ObjectOutput and give it’s reference variable name oout and call
writeObject() method and pass our employee object as parameter
[oout.writeObject(object1) ]
oout.writeObject(object1);
DESERIALIZATION :
Create object of ObjectInput and give it’s reference variable name oin and call
readObject() method [oin.readObject() ]
InputStream fin=new FileInputStream("ser.txt");
Employee emp;
emp=(Employee)oin.readObject();
SERIALIZABLE EXTERNALIZABLE
Control over It provides less control over Externalizable provides you great
Serialization Serialization as it’s not control over serialization process as
mandatory to define it is important to override
readObject() and writeExternal() and readExternal()
writeObject() methods. methods.
try {
os.writeInt(this.id);
os.writeObject(this.name);
e.printStackTrace();
}
}
try {
id=ois.readInt();
name=(String)ois.readObject();
e.printStackTrace();
}
}
We have DeSerialized id and name manually by reading them from file.
oo.writeInt(id);
oo.writeObject(name);
}
this.id=in.readInt();
this.name=(String)in.readObject();
}
Question 6. How can you avoid certain member variables of class from getting
Serialized?
Answer. Mark member variables as static or transient, and those member variables
will no more be a part of Serialization.
We can use eclipse to generate serialVersionUID for our class (as done in below
snapshot)
How to avoid warning ‘The serializable class Employee does not declare a static final
serialVersionUID field of type long’ ?
Again answer is we can use eclipse to generate serialVersionUID for our class (as
mentioned in above screenshot, click on warning button on left in line 10).
If you have serialized a class & then added few fields in it and then deserialize
already serialized version of class, how can you ensure that you don’t end up
throwing InvalidClassException?
Simply we need to define serialVersionUID in class.
When we Deserialize class ( class which has been modified after Serialization
and also class doesn’t declare SerialVersionUID) InvalidClassException is
thrown.
When we Deserialize class ( class which has been modified after Serialization
and also class declare SerialVersionUID) its gets DeSerialized successfully.
Deletion of fields.
Changing a nonstatic field to static or non transient field to transient
field. - it’s equal to deletion of fields.
Modifying the writeObject() / readObject() method - we must not modify
these method, though adding or removing them completely is compatible
change.
Question 10. What if Serialization is not available, is any any other alternative
way to transfer object over network?
Answer.
We can can convert JSON to transfer the object. JSON is helpful in stringifying
and de stringifying object.
Hibernate (ORM tool) helps in persisting object as it in database and later we
can read persisted object.
We can convert object into XML (as done in web services) and transfer object
over network.
Question 11. Why static member variables are not part of java serialization
process (Important)?
Answer. Serialization is applicable on objects or primitive data types only, but
static members are class level variables, therefore, different object’s of
same class have same value for static member.
So, serializing static member will consume unnecessary space and time.
Also, if modification is made in static member by any of the object, it won’t be
in sync with other serialized object’s value.
Question 13. What will happen if one the member of class does not implement
Serializable interface (Important)?
This is classy question which will check your in depth knowledge of Serialization
concepts. If any of the member does not implement Serializable than
NotSerializableException is thrown.
Question 14. What will happen if we have used List, Set and Map as member of
class?
This question which will check your in depth knowledge of Serialization and Java
Api’s. ArrayList, HashSet and HashMap implements Serializable interface, so if we will
use them as member of class they will get Serialized and DeSerialized as well.
Question 18. What values will int and Integer will be initialized to during
DeSerialization process if they were not part of Serialization?
int will be initialized to 0 and Integer will be initialized to null during DeSerialization
(if they were not part of Serialization process).
Question 19. How you can avoid Deserialization process creating another
instance of Singleton class (Important)?
This is another classy and very important question which will check your in depth
knowledge of Serialization and Singleton concepts. I’ll prefer you must understand
this concept in detail. We can simply use readResove() method to return same
instance of class, rather than creating a new one.
Defining readResolve() method ensures that we don't break singleton pattern during
DeSerialization process.
return INSTANCE;
}
Also define readObject() method, rather than creating new instance, assign current
object to INSTANCE like done below :
ois.defaultReadObject();
synchronized (SingletonClass.class) {
}
}
}
Question 20. Can you Serialize Singleton class such that object returned by
Deserialization process is in same state as it was during Serialization time
(regardless of any change made to it after Serialization) (Important)?
It’s another very important question which will be important in testing your
Serialization and Singleton related concepts, you must try to understand the concept
and question in detail.
YES, we can Serialize Singleton class such that object returned by Deserialization
process is in same state as it was during Serialization time (regardless of any change
made to it after Serialization)
Defining readResolve() method ensures that we don't break singleton pattern during
DeSerialization process.
}
Also define readObject() method, rather than creating new instance, assign current
object to INSTANCE like done below :
ois.defaultReadObject();
synchronized (SingletonClass.class) {
}
}
}
Question 22. How can subclass avoid Serialization if its superClass has
implemented Serialization interface (Important)?
If superClass has implemented Serializable that means subclass is also Serializable
(as subclass always inherits all features from its parent class), for avoiding
Serialization in sub-class we can define writeObject() method and throw
NotSerializableException() from there as done below.
}
You might be given code snippets in interviews and asked to give output -
Question 23. Find output of following code :
package serDeser6ListSetMap;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public MyClass(List<Integer> list, Set<Integer> set,
super();
}
@Override
return "MyClass [list=" + list + ", set=" + set + ", map=" + map +
"]";
}
list.add(2);
list.add(3);
set.add(4);
set.add(5);
try {
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");
System.out.println(object);
fin.close();
oin.close();
e.printStackTrace();
}
}
Here intention of interviewer will be to find out whether you know that list, set and
map can be serialized or not.
/*OUTPUT
*/
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
class MyClass {}
}
@Override
}
try {
oout.writeObject(object1);
System.out.println("Object Serialization completed.");
fout.close();
oout.close();
e.printStackTrace();
}
}
Here intention of interviewer will be to find out whether you know that if any of the
member does not implement Serializable than NotSerializableException is thrown.
/*OUTPUT
java.io.NotSerializableException: SerDeser10memberNotSer.MyClass
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at
SerDeser10memberNotSer.SerializeConstructorCheck.main(SerializeConstructorCheck.ja
va:42)
*/