Interview questions on Serialization in Java

Sanjay Singh
4 min readFeb 19, 2020

--

What is Serialization in Java
Object convert into a binary format — Serialization
binary convert into Object — de-serialization

If you have Student class and it is Serializable
and I have one more class Adress and it is not Serializable

class Student imp Serializable{
private String name;
private Address address;
}
class Adress{
private String city;
}

If we are trying to make object Serialize then what happen
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class UseExample {
public static void main(String[] args) throws IOException {
Student student = new Student(“BOX”, new Address(“Action”, “Noida”));
String filename = “file.ser”;
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(student);
out.close();
file.close();
System.out.println(out);

}}
Output Exception at run time
Exception in thread “main” java.io.NotSerializableException:
com.testing.serlization.Address
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)

Solution: we make Address object also Serialize

How to make a Java class Serializable?

Making a class Serializable in Java is very easy, Your Java class just needs to implements java.io.Serializable interface and JVM will take care of serializing object in default format.
What is serialVersionUID? What would happen if you don’t define this?
SerialVersionUID is an unique id ,which is stamped on object when it get serialized usually hashcode of object.
SerialVersionUID is used for version control of object

If you write serialVersionUID without implimeting Serializable interface then it not throw any kind of error .only show message The value of the field Utility.serialVersionUID is not used it means understand simple variable.
private static final long serialVersionUID = 1L;

Which kind of variables is not serialized during Java Serialization?
static and transient variable.
static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process
Transient variables are also not included in java serialization process and are not the part of the object’s serialized state

What is use of serialVersionUID?
default Java serialization mechanism writes the metadata about the object,which includes the class name,field names and types, and superclass
Everytime an object is serialized the java serialization mechanism automatically computes a hash value.
ObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved
the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Following is the list of changes which are compatible:
Add fields
Change a field from static to non-static
Change a field from transient to non-transient
Add classes to the object tree

List of incompatible changes:
Delete fields
Change class hierarchy
Change non-static to static
Change non-transient to transient
Change type of a primitive field

So, if no suid is present, inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .

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.

What happens if an object is serializable but it includes a reference to a non-serializable object?
public class NonSerial {
//This is a non-serializable class}
public class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
private NonSerial nonSerial;}

then what happen?
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.

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.

Object Serialization with Inheritance in Java

Case 1: If superclass is serializable then subclass is automatically serializable

If superclass is Serializable, then by default every subclass is serializable. Hence, even though subclass doesn’t implement Serializable interface( and if it’s superclass implements Serializable), then we can serialize subclass object.

If a superclass is not serializable then subclass can still be serialized -What happens when a class is serializable but its superclass is not ?
Serialization-At the time of serialization, if any instance variable is inheriting from non-serializable superclass, then JVM ignores original value of that instance variable and save default value to the file.

De- Serialization- At the time of de-serialization, if any non-serializable superclass is present then JVM will execute instance control flow in the superclass.
JVM will always invoke default(no-arg) constructor of that class
So every non-serializable superclass must necessarily contain default constructor, otherwise we will get runtime-exception.

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet