Java Interview Questions - Serialization
1. What is serialization in java ?
The reverse process of creating object from binary stream is called deserialization in Java.
Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.
Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running java virtual machine.
The reverse process of creating object from binary stream is called deserialization in Java.
Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.
2. What is the need of Serialization?
- To send state of one or more object’s state over the network through a socket.
- To save the state of an object in a file.
- An object’s state needs to be manipulated as a stream of bytes.
3. Do we need to implement any method of Serializable interface to make an object serializable?
No. Serializable is a Marker Interface. It does not have any methods.
4. How would you exclude a field of a class from serialization or what is a transient variable? What is the common use?
Transient variables cannot be serialized. The fields marked transient in a serializable object will not be transmitted in the byte stream. An example would be a file handle, a database connection, a system thread etc. Such objects are only meaningful locally. So they should be marked as transient in a serializable class.
5. Are the static variables saved as the part of serialization?
No. The static variables belong to the class are not the part of the state of the object so they are not saved as the part of serialized object.
6. What will be the value of transient variable after de-serialization?
It’s default value. e.g. if the transient variable in question is an int, it’s value after deserialization will be zero.
public class TestTransientVal implements Serializable {
private static final long serialVersionUID = -22L;
private String name;
transient private int age;
TestTransientVal(int age, String name) {
this.age = age;
this.name = name;
}
public static void main(String [] args) {
TestTransientVal c = new TestTransientVal(1,"ONE");
System.out.println("Before serialization:" + c.name + " "+ c.age);
try {
FileOutputStream fs =new FileOutputStream("testTransient.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis =new FileInputStream("testTransient.ser");
ObjectInputStream ois =new ObjectInputStream(fis);
c = (TestTransientVal) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After de-serialization:" + c.name +" "+ c.age);
}
}
Result of executing above piece of code –
Before serialization: - Value of non-transient variable ONE Value of transient variable 1
After de-serialization:- Value of non-transient variable ONE Value of transient variable 0
Before serialization: - Value of non-transient variable ONE Value of transient variable 1
After de-serialization:- Value of non-transient variable ONE Value of transient variable 0
Explanation –
The transient variable is not saved as the part of the state of the serailized variable, it’s value after de-serialization is it’s default value.
The transient variable is not saved as the part of the state of the serailized variable, it’s value after de-serialization is it’s default value.
7. How can one customize the Serialization process? or What is the purpose of implementing the writeObject() and readObject() method?
When you want to store the transient variables state as a part of the serialized object at the time of serialization the class must implement the following methods –
private void wrtiteObject(ObjectOutputStream outStream) {
//code to save the transient variables state
//as a part of serialized object
}
private void readObject(ObjectInputStream inStream) {
//code to read the transient variables state
//and assign it to the de-serialized object
}
public class TestCustomizedSerialization implements Serializable {
private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;
TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}
private void writeObject(ObjectOutputStream os) {
try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
}
private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
int noOfTransients = (is.readInt());
} catch (Exception e) {
e.printStackTrace(); }
}
public int getNoOfTranVar() {
return noOfTranVar;
}
The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object manually by implementing writeObject() and restored by implementing readObject().
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.
8. If a class is serializable but its superclass in not, what will be the state of the instance variables inherited from super class after deserialization?
The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run.
E.g.
public class ChildSerializable extends ParentNonSerializable implements Serializable {
private static final long serialVersionUID = 1L;
String color;
ChildSerializable() {
this.noOfWheels = 8;
this.color = "blue";
}
}
public class SubSerialSuperNotSerial {
public static void main(String [] args) {
ChildSerializable c = new ChildSerializable();
System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
try {
FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("superNotSerail.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (ChildSerializable) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After :- " + c.noOfWheels + " "+ c.color);
}
}
Result on executing above code –
Before : - 8 blue
After :- 4 blue
The instance variable ‘noOfWheels’ is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.
9. What happens if an object is serializable but it includes a reference to a non-serializable object?
Ans- If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.
public class NonSerial {
//This is a non-serializable class
}
public class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
private NonSerial nonSerial;
MyClass(NonSerial nonSerial){
this.nonSerial = nonSerial;
}
public static void main(String [] args) {
NonSerial nonSer = new NonSerial();
MyClass c = new MyClass(nonSer);
try {
FileOutputStream fs = new FileOutputStream("test1.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("test1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MyClass) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
On execution of above code following exception will be thrown;
java.io.NotSerializableException: NonSerial
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)
10. To serialize an array or a collection all the members of it must be serializable. True /False?
True.
Comments
Post a Comment