0% found this document useful (0 votes)
3 views

Serialization in Java

Serialization in Java is the process of converting an object into a byte stream for storage or transmission, while deserialization is the reverse process. It is essential for preserving object state across JVM restarts and for transferring objects over networks. Key concepts include the Serializable interface, serialVersionUID for version control, and the differences between serialization and externalization, which allows for more control over the serialization process.

Uploaded by

Utkarsh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Serialization in Java

Serialization in Java is the process of converting an object into a byte stream for storage or transmission, while deserialization is the reverse process. It is essential for preserving object state across JVM restarts and for transferring objects over networks. Key concepts include the Serializable interface, serialVersionUID for version control, and the differences between serialization and externalization, which allows for more control over the serialization process.

Uploaded by

Utkarsh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Serialization in java

Why serialization is used in Java?


Serialization in Java allows us to convert an Object to stream that we can send over
the network or save it as file or store in DB for later usage. Deserialization is the
process of converting Object stream to actual Java Object to be used in our program.

What is the need of Serialization ?


 In Java, everything is Object. So, these objects represent state (or data) which resides inside
heap memory of JVM machine running on RAM memory
 Whenever JVM shuts, then these states (or data) are lost
 So, to preserve these state (or data) once again JVM restarts, we need serialization to
serialize objects in binary format
 In addition, to transfer over network channels Objects need to be converted into binary
format. For this purpose also, serialization concept is very useful

Can we serialize ArrayList in Java?


In Java, ArrayList class is serializable by default. It essentially means that we do not
need to implement Serializable interface explicitly in order to serialize ArrayList. We
can directly use ObjectOutputStream to serialize ArrayList, and ObjectInputStream
to deserialize an arraylist object.

What is serialVersionUID in Java?


Simply put, the serialVersionUID is a unique identifier for Serializable classes. This is
used during the deserialization of an object, to ensure that a loaded class is compatible
with the serialized object. If no matching class is found, an InvalidClassException is
thrown

Why do we use serialVersionUID?


Why so we use SerialVersionUID : SerialVersionUID is used to ensure that during
deserialization the same class (that was used during serialize process) is loaded. ...
Serialization : At the time of serialization, with every object sender side JVM will save a
Unique Identifier.
Serialization in java

What is externalization in Java?


What is Externalization in Java? Externalization in Java is used whenever you need
to customize the serialization mechanism. If a class implements an Externalizable
interface, then serialization of the object will be done using the method writeExternal().

When do you use Externalization?


If you want to serialize only part of an object, then Externalization is the best option. You
will have to serialize only required fields of an object.

Example:

1 public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException {


2 this.code = in.readInt();
3 this.name = (String) in.readObject();
4 this.password = (String) in.readObject();
this.birthday = (Date) in.readObject();
5
}
6

Parameters Externalization Serialization


Process Uses Custom Serialization process Uses Default serialization process
UID No need of a UID It needs serialVersionUID
You have to store the data which have an
Storage You can store the object directly
object
The externalizable interface provides
complete control of the serialization
Access No such access
process to application.

Is list serializable in Java?


List does not implement Serializable because is it not a key requirement for a list.
There is no guarantee (or need) that every possible implementation of a List can
Serialization in java

be serialized. LinkedList and ArrayList choose to do so, but that is specific to their
implementation

Is array serializable Java?


Both arrays and ArrayList are serializable. As for performance, that's an entirely
different topic. Arrays, especially of primitives, use quite a bit less memory than
ArrayLists, but the serialization format is actually equally compact for both.

What is serialVersionUID what would happen if you don't define this?


serialVersionUID is used for version control of object. ... Consequence of not
specifying serialVersionUID is that when you add or modify any field in class then
already serialized class will not be able to recover
because serialVersionUID generated for new class and for old serialized object will be
different.

Explain serialVersionUID ?
 Whenever we declare any class implementing Serializable interface, then it always
prompts/warns to include/declare serialVersionUID which is of type long with modifier
final and static
 Along with serialized object, this variable also gets serialized and during de-serialization both
serialVersionUID compared (stored serialVersionUID & value present inside declared class)
and then it converted back
 If there is any mismatch, then InvalidClassException is thrown
 Note: any changes to class results in change of serialVersionUID
 Therefore, it is highly recommended to declare this value instead allowing compiler to
generate for us

What will happen if one of the members in the class doesn't implement serializable
interface?
Question: What happens if one of the members in a class does not implement
Serializable interface? Answer: When you try to serialize an object
which implements Serializable interface, incase if the object includes a reference
of an non serializable object then NotSerializableException will be thrown.

Why Serializable interface is called Marker interface in Java ?


 Any interface in Java which doesn’t contains any methods is known as marker interface
 Likewise, Serializable interface doesn’t contain any methods therefore it is also known as
Marker interface

Serialization affects the very basics of Singleton design pattern, how can we
overcome to stop class to be serialized ?
 Whenever Object is serialized and then again de-serialized then new object is created which
breaks basic principle of Singleton class
Serialization in java

 Therefore, it is highly recommended to override readResolve(); method and return same


INSTANCE every time
 So that, no new object is created, and it says true to Singleton property

In Parent-child class relationship, if parent doesn’t implements Serializable


interface but child implements Serializable interface, then what will happen if
child class is serialized ?
 We should understand whether is it possible to serializable sub class, if
it’s super class isn’t serializable ?
 The answer is yes, because if condition to serialize any class on the basis of its super class
implementing java.io.Serializable interface, then no class in Java can be
serialized
 Reason: java.lang.Object is the base class for any class defined in Java, and
it doesn’t implements java.io.Serializable interface
 In that way, it is very well possible to serialize a sub class even if its super
class doesn’t implement java.io.Serializable interface
 But parent-class attributes will be ignored

How to stop serialization ?


 To stop serialization, override writeObject(); method explicitly throw “No
Serialization is allowed” exception

In Parent-child class relationship, if parent implements Serializable interface


and child doesn’t implements Serializable interface, then whether child class
is serializable ?
 For any object to be serialized, corresponding class must be serializable
 Otherwise, NotSerializableException will be thrown at run time, although program
compiles successfully
 In this scenario, as parent-class is already implementing Serializable interface therefore,
all extending sub-classes automatically implements Serializable interface through
inheritance relationship
 Therefore, for above question child-class serializes successfully

https://www.benchresources.net/serialization-interview-question-and-answer-in-java/
Whether order of serialization & de-serialization need to be same? What
happens, if order is missed ?
 Order of Serializationis very important to know, because we need to follow same
order while de-serializing objects
 If Order of Serialization is unknown, then it may
throw java.lang.ClassCastException
 To overcome ClassCastException, we can 1st check type of object
using instanceOf operator and then assign it to proper class after doing
necessary type-casting
 Exception: iterating through while loop may throw EOFException, we need catch this
exception and handle it properly

while((object = ois.readObject()) != null){


if(object instanceof Customer)
Serialization in java

deSerializeCustomer = (Customer) object;


else if(object instanceof Employee)
deSerializeEmployee = (Employee) object;
else if(object instanceof Student)
deSerializeStudent = (Student) object;
} // END of while loop
}

Which modifier stops variables to be serialized ?


 Transient modifier stops variables to be serialized
 During de-serialization, it returns with default value
 Like, 0 for int data-type, null for String, false for Boolean data-type, etc.

Serialization with Inheritance


Case 1: Super-class implements java.io.Serializable but sub-class doesn’t
implement java.io.Serializable
 When super-class is serializable, then any class that is extending super-class will
also be serializable by default through inheritance principle
 So, here sub-class doesn’t required to implement java.io.Serializable explicitly
 When sub-class is serialized, then sub-class properties as well as inherited super-
class properties will also be serialized during serialization process
 Note: To prevent sub class from serializing by default, then we need to
override writeObject() and readObject() methods

Case 2: Sub-class implements java.io.Serializable but super-class doesn’t


implement java.io.Serializable

Serialization process:
 While serializing sub-class, JVM will check if there are any super-class which isn’t
implementing java.io.Serializable interface
 Then, inheriting instance variables of non-serializable super-class will be stored
to default value ignoring their original values
 Like 0 for Integer, null for String, etc

De-Serialization process:
 While de-serializing sub class, JVM will check if there are any non-serializable super-
class
 Then, it will execute instance initialization flow (i.e.; similar to object
instantiation flow)
Serialization in java

 1st check: if there are direct initialization at instance variable declaration


 2nd check: if there are any initialization block for instance variable assignment
 3rd check: invokes no-argument constructor and looks for instance variable
assignment
 To execute 3rd check, non-serializable super-class requires no-argument
constructor
 Exception: otherwise InvalidClassException will be thrown
 Note: For any other case, constructor is not invoked with only exception being
for non-serializable super-class
 Serializing & De-Serializing sub-class PrivilegedCustomer

Important points about Serialization Order:


 Rule 1: all classes that need to be serialized must
implement java.io.Serializable interface
 Order of Serialization is very important to know, because we need to follow
the same order while de-serializing objects
 If Order of Serialization is unknown, then it may
throw java.lang.ClassCastException
 To overcome ClassCastException, we can 1st check type of object
using instanceOf operator and then assign it to proper class after doing
necessary type-casting
 Exception: iterating through while loop may throw EOFException, we need catch this
exception and handle it properly

Important points to remember while Serialization with Aggregation classes:


 Rule 1: all classes that need to be serialized must
implement java.io.Serializable interface
 Rule 2: All reference classes inside a serializable class must also
be java.io.Serializable
 Rule 3: If any of the class is not implementing java.io.Serializable in the serialization
process, then JVM will throw NotSerializableException

Are the constructors in an object invoked when it is


de-serialized?
No. When a class is De-serialized, initialization (constructor’s, initializer’s) does not take place. The

state of the object is retained as it is.


if Serializable has been implemented - constructor is not called during DeSerialization
process.
But, if Externalizable has been implemented - constructor is called during DeSerialization
process.
Serialization in java

Are the values of static variables stored when an


object is serialized?
Static Variables are not part of the object. They are not serialized.

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.

Is constructor of super class called during DeSerialization process of


subclass (Important)?
Answer.
If superclass has implemented Serializable - constructor is not called during DeSerialization
process.
If superclass has not implemented Serializable - constructor is called during DeSerialization
process.

What values will int and Integer will be initialized to during


DeSerialization process if they were not part of Serialization?
Answer. int will be initialized to 0 and Integer will be initialized to null during DeSerialization
(if they were not part of Serialization process).
How can subclass avoid Serialization if its superClass has
implemented Serialization interface (Important)?
Answer. 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.
private void writeObject(ObjectOutputStream os) throws
NotSerializableException {
throw new NotSerializableException("This class cannot be
Serialized");
}
Serialization in java

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.

when to add readObjectNoData() during serialization?

 5. When you implement a class with instance fields that is


serializable and extendable.

Note: When a class has instance fields which are serializable and
extendable, there is a caution you should be aware of. If the class has
invariants that would be violated if its instance fields were initialized to
their default values (zero for integral types, false for boolean, and null
for object reference types)

Changes to a serializable class can be compatible or incompatible. 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
Serialization in java

How can one customize the Serialization process? or What is the purpose of
implementing the writeObject() and readObject() method?
Ans) 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 –

What are differences between Serializable and Externalizable in Java?


Answer :
Parameter Serializable Externalizable
It is marker interface. You Externalizable is not
don’t have to provide marker interface, you have
implementation of any to override writeExternal
Marker interface method. and readExternal method.
Serializable interface has Externalizable interface
less control over has more control over
serialization process and it serialization process and it
is optional to override is mandatory to override
readObject and writeExternal and
Control writeObject. readExternal.
Programmer have to
JVM uses reflection to implement readExternal
perform serialization in the and writeExternal
case of Serializable methods but it relatively
interface which is quite results in better
Performance slow. performance
Supersedes NA If you implement
Externalizable interface
and provide
implementation of
readExternal and
writeExternal then it
supersedes readObject
Serialization in java

and writeObject methods


in that class. It is due to
the fact that Externalizable
extends Serializable
interface.
Default constructor is not Default constructor is
Constructor called during called during called during
Deserialization Deserialization process. Deserialization process.

Rules for Transient Variable vs Static


Variable
1. Transient variable will be ignored during serialization.
2. Static variable won’t even participate in Serialization.
3. Static variable will be serialized if the value is initialized during declaration itself.
4. If a variable contains both transient and static keyword, also if the value is
initialized during declaration, then it will be serialized. Because here transient
modifier will be ignored and static modifier will take over the actions.
5. Final variable will be serialized.
6. If a variable contains both final and transient keyword, then it will be serialized.
Because here transient modifier will be ignored and final modifier will take over
the actions.

TransientStaticVariable .java
package com.learnfromexamples.transientvsstatic;

import java.io.Serializable;

public class TransientStaticVariable implements Serializable{

public TransientStaticVariable() {
System.out.println("Constructorr Called...");
}
public transient String variableOne;
public transient String variableTwo = "V2";
public static String variableThree;
Serialization in java

public static String variableFour = "V4";


public transient static String variableFive;
public transient static String variableSix = "V6";
final String variableSeven = "V7";
transient final String variableEight = "V8";
}

Serialization.java
package com.learnfromexamples.transientvsstatic;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Serialization {

public static void main(String[] args) throws IOException {


TransientStaticVariable staticVariable = new TransientStaticVariable();
staticVariable.variableOne = "V11";
staticVariable.variableTwo = "V22";
staticVariable.variableThree = "V33";
staticVariable.variableFour = "V44";
staticVariable.variableFive = "V55";
staticVariable.variableSix = "V66";
// since variableSeven and variableEight are final we can't reassign the values
//staticVariable.variableSeven = "V77";
//staticVariable.variableEight = "V88";

FileOutputStream fileOutputStream = new FileOutputStream("transientstatic.ser");


ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(staticVariable);
}

}
Output
Constructorr Called...
Deserialization.java
package com.learnfromexamples.transientvsstatic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class DeSerialization {

public static void main(String[] args) throws IOException, ClassNotFoundException {


Serialization in java

FileInputStream fileInputStream = new FileInputStream("transientstatic.ser");


ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
TransientStaticVariable staticVariable = (TransientStaticVariable)objectInputStream.readO
System.out.println("After Deserialization...");
System.out.println(staticVariable.variableOne);
System.out.println(staticVariable.variableTwo);
System.out.println(staticVariable.variableThree);
System.out.println(staticVariable.variableFour);
System.out.println(staticVariable.variableFive);
System.out.println(staticVariable.variableSix);
System.out.println(staticVariable.variableSeven);
System.out.println(staticVariable.variableEight);
}

}
Output
After Deserialization...
null
null
null
V4
null
V6
V7
V8

You might also like