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

Serialization

The document discusses serialization in Java, which is the process of converting an object into a byte stream. It can serialize objects to transfer them over a network, save to a file, or save to a database. The document also provides code examples for serializing and deserializing objects in Java.

Uploaded by

Pradeep Navalgi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Serialization

The document discusses serialization in Java, which is the process of converting an object into a byte stream. It can serialize objects to transfer them over a network, save to a file, or save to a database. The document also provides code examples for serializing and deserializing objects in Java.

Uploaded by

Pradeep Navalgi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

What is Serialization in java?

www.javamadesoeasy.com /2015/07/what-is-serialization-in-java.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Lets start serialization tutorial by understanding what is Serialization. Serialization is process of converting object
into byte stream.

Serialized object (byte stream) can be:


>Transferred over network.
>Persisted/saved into file.
>Persisted/saved into database.

Once, object have have been transferred over network or persisted in file or in database, we could deserialize the
object and retain its state as it is in which it was serialized.

In series of Serialization tutorial well read following topics in depth with programs >

Serializing & DeSerializing >


Serialize and DeSerialize object

Customizing Serialization process by implementing Serializable and Externalizable/ Difference between them >
Customize Serialization process by defining writeObject() method & DeSerialization process by defining
readObject() method

Serialize and DeSerialize object by implementing Externalizable interface- override writeExternal() and
readExternal() methods

Difference between Externalizable and Serialization interface in java

serialVersionUID >
Impact of not defining serialVersionUID in class and avoiding InvalidClassException

Constructor call during DeSerialization >


Is constructor of class called during DeSerialization process

Is constructor of super class called during DeSerialization process of sub class

Serializing and DeSerializing Singleton >


Avoid Deserialization process creating another instance of Singleton class

1/2
Preserving Singletons state during DeSerialization >
Can you Serialize Singleton class such that object returned by Deserialization process is in same state as it was
during Serialization time

Serializing and DeSerializing primitive data types >


Are primitive types part of serialization process

What values will int and Integer will be initialized to during DeSerialization process if they were not part of
Serialization

Serializing class of Collection Apis >


can list, set and maps be Serialized and DeSerialized

Static and Transient are not serialized >

Significance of using Static and Transient member variables - Static and Transient are not
serialized in java

compatible and incompatible changes in Serialization and deSerialization >

compatible and incompatible changes in Serialization and deSerialization process in java

Deep copy in java using Serialization and Deserialization >

Deep copy in java using Serialization and Deserialization

2/2
Serialize and DeSerialize object in java - An explanation Full
programs
www.javamadesoeasy.com /2015/02/serialize-and-deserialize-object.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

In order to serialize object our class needs to implement java.io.Serializable interface. Serializable interface is
Marker interface i.e. it does not have any methods of its own, but it tells Jvm that object has to converted into byte
stream.

SERIALIZATION>
Create object of ObjectOutput and give its reference variable name oout and call writeObject() method and pass our
employee object as parameter [oout.writeObject(object1) ]

OutputStream fout = new FileOutputStream("ser.txt");


ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects... ");
oout.writeObject(object1);

Full Program/SourceCode to Serialize Object>

1/5
package SerDeser1;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;
private String name;
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee(1, "amy");
Employee object2 = new Employee(2, "ankit");
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
oout.writeObject(object2);
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
*/

DESERIALIZATION>
Create object of ObjectInput and give its reference variable name oin and call readObject() method
[oin.readObject() ]

2/5
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, displaying employee objects..." );
Employee emp;
emp=(Employee)oin.readObject();

Full Program/SourceCode to DeSerialize object>

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
public class DeSerializeEmployee {
public static void main(String[] args) {
InputStream fin;
try {
fin = new FileInputStream("ser.txt");
ObjectInput oin = new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, "
+ "displaying employee objects...");
Employee emp;
while ((emp = (Employee) oin.readObject()) != null) {
System.out.println(emp);
}
oin.close();
} catch (EOFException e) {
System.out.println("File ended");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Object DeSerialization completed.");
}
}
/*OUTPUT
DeSerialization process has started, displaying employee objects...
Employee [id=1, name=amy]
Employee [id=2, name=ankit]
File ended
Object DeSerialization completed.
*/

In the above program when file is read till end using readObject() in while loop then EOFException is thrown. Java
Api doesnt provide any elegant solution to signify end the file. Please read this post where well discuss the best

3/5
possible solution to address the problem : Avoid ObjectInputStream.readObject() from throwing EOFException at
End Of File in java

RELATED LINKS>

Serialization And Deserialization Tutorial

Serializing & DeSerializing >


Serialize and DeSerialize object

Customizing Serialization process >


Customize Serialization process by defining writeObject() method & DeSerialization process by defining
readObject() method

Serialize and DeSerialize object by implementing Externalizable interface- override writeExternal() and
readExternal() methods

serialVersionUID >
Impact of not defining serialVersionUID in class and avoiding InvalidClassException

Interviews >
Serialization - Top 25 interview questions (detailed explanation with programs)

4/5
5/5
Avoid ObjectInputStream.readObject() from throwing
EOFException at End Of File in java
www.javamadesoeasy.com /2015/09/avoid-objectinputstreamreadobject-from.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Before going into this post Ill strongly recommend you to have knowledge of how objects are Serialized and
DeSerialized in java.

During deserialization process when file is read till end using readObject() in while loop then EOFException is
thrown as we saw in DeSerialization program. Java Api doesnt provide any elegant solution to signify end the file.
Generally what we could except at EOF(end of file) is null but that doesnt happen.

So, well try to address the problem because catching EOFException and interpreting it as EOF is not the elegant
solution because sometimes you may fail to detect a normal EOF of a file that has been truncated.

So, lets discuss best possible solution to address the problem >

Solution 1) You may persist some count in file during serialization process to find out exactly how many object
were actually serialized and simply use for loop in place of while loop in deserialization process.

Or,

Solution 2) Ill recommend you this solution, probably the best solution

Create a class EofIndicatorClass which implements Serializable interface.


During serialization >

Write instance of EofIndicatorClass at EOF during serialization to indicate EOF during


deSerialization process.

During serialization >

If oin.readObject() returns instanceof EofIndicatorClass that means it's EOF , exit while loop and
EOFException will not be thrown.

Full Program to Serialize Object and persisting EofIndicatorClass at EOF >

1/4
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 whose instance will be written at EOF during serialization
* to indicate EOF during deSerialization process.
*/
class EofIndicatorClass implements Serializable{}
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [name=" + name + "]";
}
}
/*
* Serialization class
*/
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee( "amy");
Employee object2 = new Employee( "ankit");
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, "
+ "serializing employee objects...");
oout.writeObject(object1);
oout.writeObject(object2);

//write instance of EofIndicatorClass at EOF


oout.writeObject(new EofIndicatorClass());
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
*/

2/4
Full Program to DeSerialize object and detecting EOF without throwing EOFException >
Avoid ObjectInputStream.readObject() from throwing EOFException at End Of File in java

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class DeSerializeEmployee {
public static void main(String[] args) {
InputStream fin;
try {
fin = new FileInputStream("ser.txt");
ObjectInput oin = new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, "
+ "displaying employee objects...");
/*
*If oin.readObject() returns instanceof EofIndicatorClass that means
*it's EOF, exit while loop and EOFException will not be thrown.
*/
Object obj;
while(!((obj = oin.readObject()) instanceof EofIndicatorClass)){
System.out.println(obj);
}
oin.close();
} catch (EOFException e) {
System.out.println("File ended");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Object DeSerialization completed.");
}
}
/*OUTPUT
DeSerialization process has started, displaying employee objects...
Employee [name=amy]
Employee [name=ankit]
Object DeSerialization completed.
*/

If you note output of program EOFException wasnt thrown, you may compare output of the program with
DeSerialization done in this post where EOFException was thrown.

3/4
4/4
Customize Serialization process by defining writeObject()
method & DeSerialization process by defining readObject()
method in java
www.javamadesoeasy.com /2015/02/customize-serialization-process-by.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

We can customize Serialization process by defining writeObject() method & DeSerialization process by defining
readObject() method.

Read : Serialize and DeSerialize object

Lets customize Serialization process by defining writeObject() method :

private void writeObject(ObjectOutputStream os) {


System.out.println("In, writeObject() method.");
try {
os.writeInt(this.id);
os.writeObject(this.name);
} catch (Exception e) {
e.printStackTrace();
}
}

We have serialized id and name manually writing them in file.

Lets customize DeSerialization process by defining readObject() method :

private void readObject(ObjectInputStream ois) {


System.out.println("In, readObject() method." );
try {
id=ois.readInt();
name=(String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}

We have DeSerialized id and name manually by reading them from file.

1/4
Full Program/SourceCode to customize Serialization process by defining readObject() method & DeSerialization
process by defining writeObject() method>

package SerDeser2DefineReadWriteObject;
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;

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;
private String name;
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}

/*
* define how Serialization process will write objects.
*/
private void writeObject(ObjectOutputStream os) {
System.out.println("In, writeObject() method.");
try {
os.writeInt(this.id);
os.writeObject(this.name);
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* define how deSerialization process will read objects.
*/
private void readObject(ObjectInputStream ois) {
System.out.println("In, readObject() method." );
try {
id=ois.readInt();
name=(String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}

}
public class SerializeEmployee {
public static void main(String[] args) {
2/4
Employee object1 = new Employee(1, "amy");
Employee object2 = new Employee(2, "ankit");

try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
oout.writeObject(object2);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}

//Start deSerialization process.


try{
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);

System.out.println("\nDeSerialization process has started, displaying deSerialized employee


objects...");
Employee emp;
while( (emp=(Employee)oin.readObject())!=null ){
System.out.println(emp);
}
fin.close();
oin.close();

}catch(IOException | ClassNotFoundException e){


//e.printStackTrace();
}
System.out.println("Object DeSerialization completed.");

}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
In, writeObject() method.
In, writeObject() method.
Object Serialization completed.
DeSerialization process has started, displaying deSerialized employee objects...
In, readObject() method.
Employee [id=1, name=amy]
In, readObject() method.
Employee [id=2, name=ankit]
Object DeSerialization completed.
*/

In above program we have customized Serialization process by defining methods like readObject() and
writeObject() .

3/4
4/4
Serialize and DeSerialize object by implementing
Externalizable interface- override writeExternal() and
readExternal() methods in java
www.javamadesoeasy.com /2015/02/serialize-and-deserialize-object-by.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

For serializing object by implementing Externalizable interface, we need to override writeExternal() and
readExternal() for serialization process to happen.

For Serialization process override writeExternal() method & for DeSerialization process by override readExternal()
method.

Lets customize Serialization process by overriding writeExternal() method :

public void writeExternal(ObjectOutput oo) throws IOException {


System.out.println("in writeExternal()");
oo.writeInt(id);
oo.writeObject(name);
}

We have serialized id and name manually by writing them in file.

Lets customize DeSerialization process by overriding readExternal() method :

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


System.out.println("in readExternal()");
this.id=in.readInt();
this.name=(String)in.readObject();
}

We have DeSerialized id and name manually by reading them from file.

Full Program/SourceCode to Serialize Object by calling writeExternal() method of Externalizable interface >

package SerDeser3ImplementExternalizable;
import java.io.Externalizable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
1/4
class Employee implements Externalizable {

private static final long serialVersionUID = 1L;


private Integer id;
private String name;
public Employee(){} //This constructor is called during deSerializaition process, as we have implemented
Externalizable.

public Employee(Integer id, String name) {


this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}

/*
* define how Serialization process will write objects.
*/
@Override
public void writeExternal(ObjectOutput oo) throws IOException {
System.out.println("in writeExternal()");
oo.writeInt(id);
oo.writeObject(name);
}

/*
* define how deSerialization process will read objects.
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("in readExternal()");
this.id=in.readInt();
this.name=(String)in.readObject();
}

}
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee(1, "amy");
Employee object2 = new Employee(2, "ankit");

try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);

System.out.println("Serialization process has started, serializing employee objects..." );


oout.writeObject(object1);
oout.writeObject(object2);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}

2/4
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
in writeExternal()
in writeExternal()
Object Serialization completed.
*/

Full Program/SourceCode to DeSerialize object by calling readExternal() method of Externalizable interface >

package SerDeser3ImplementExternalizable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
public class DeSerializeEmployee {

public static void main(String[] args){


try{
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);

System.out.println("DeSerialization process has started, displaying deSerialized employee objects..." );


//while( oin.readObject()!=null );
Employee emp;
while( (emp=(Employee)oin.readObject())!=null ){
System.out.println(emp);
}
fin.close();
oin.close();

}catch(IOException | ClassNotFoundException e){


//e.printStackTrace();
}
System.out.println("Object DeSerialization completed.");

}
}
/*OUTPUT
DeSerialization process has started, displaying deSerialized employee objects...
in readExternal()
Employee [id=1, name=amy]
in readExternal()
Employee [id=2, name=ankit]
Object DeSerialization completed.
*/

3/4
4/4
Serialize and DeSerialize object by implementing
Externalizable interface- override writeExternal() and
readExternal() methods in java
www.javamadesoeasy.com /2015/02/serialize-and-deserialize-object-by.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

For serializing object by implementing Externalizable interface, we need to override writeExternal() and
readExternal() for serialization process to happen.

For Serialization process override writeExternal() method & for DeSerialization process by override readExternal()
method.

Lets customize Serialization process by overriding writeExternal() method :

public void writeExternal(ObjectOutput oo) throws IOException {


System.out.println("in writeExternal()");
oo.writeInt(id);
oo.writeObject(name);
}

We have serialized id and name manually by writing them in file.

Lets customize DeSerialization process by overriding readExternal() method :

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


System.out.println("in readExternal()");
this.id=in.readInt();
this.name=(String)in.readObject();
}

We have DeSerialized id and name manually by reading them from file.

Full Program/SourceCode to Serialize Object by calling writeExternal() method of Externalizable interface >

package SerDeser3ImplementExternalizable;
import java.io.Externalizable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
1/4
class Employee implements Externalizable {

private static final long serialVersionUID = 1L;


private Integer id;
private String name;
public Employee(){} //This constructor is called during deSerializaition process, as we have implemented
Externalizable.

public Employee(Integer id, String name) {


this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}

/*
* define how Serialization process will write objects.
*/
@Override
public void writeExternal(ObjectOutput oo) throws IOException {
System.out.println("in writeExternal()");
oo.writeInt(id);
oo.writeObject(name);
}

/*
* define how deSerialization process will read objects.
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("in readExternal()");
this.id=in.readInt();
this.name=(String)in.readObject();
}

}
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee(1, "amy");
Employee object2 = new Employee(2, "ankit");

try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);

System.out.println("Serialization process has started, serializing employee objects..." );


oout.writeObject(object1);
oout.writeObject(object2);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}

2/4
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
in writeExternal()
in writeExternal()
Object Serialization completed.
*/

Full Program/SourceCode to DeSerialize object by calling readExternal() method of Externalizable interface >

package SerDeser3ImplementExternalizable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
public class DeSerializeEmployee {

public static void main(String[] args){


try{
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);

System.out.println("DeSerialization process has started, displaying deSerialized employee objects..." );


//while( oin.readObject()!=null );
Employee emp;
while( (emp=(Employee)oin.readObject())!=null ){
System.out.println(emp);
}
fin.close();
oin.close();

}catch(IOException | ClassNotFoundException e){


//e.printStackTrace();
}
System.out.println("Object DeSerialization completed.");

}
}
/*OUTPUT
DeSerialization process has started, displaying deSerialized employee objects...
in readExternal()
Employee [id=1, name=amy]
in readExternal()
Employee [id=2, name=ankit]
Object DeSerialization completed.
*/

3/4
4/4
Difference between Externalizable and Serialization
interface in java
www.javamadesoeasy.com /2015/07/difference-between-externalizable-and.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

In previous articles we read how to Customize Serialization process by defining writeObject() method &
DeSerialization process by defining readObject() method and Serialize and DeSerialize object by implementing
Externalizable interface- override writeExternal() and readExternal() methods

Now, let's figure out difference between SERIALIZABLE and EXTERNALIZABLE >

SERIALIZABLE EXTERNALIZABLE

Methods It is a marker interface it doesnt have Its not a marker interface.


any method. It has methods called writeExternal() and
readExternal()

Default Serialization YES, Serializable provides its own NO, we need to override writeExternal() and
process default serialization process, we just readExternal() for serialization process to
need to implement Serializable happen.
interface.

Customize We can customize default serialization Serialization process is completely customized


serialization process by defining following methods We need to override Externalizable interfaces
process in our class >readObject() and writeExternal() and readExternal() methods.
writeObject()
Note: We are not overriding these
methods, we are defining them in our
class.

Control over It provides less control over Externalizable provides you great control over
Serialization Serialization as its not mandatory to serialization process as it is important to
define readObject() and writeObject() override writeExternal() and readExternal()
methods. methods.

Constructor call Constructor is not called during Constructor is called during deSerialization.
during deSerialization.
deSerialization

1/2
2/2
What is serialVersionUID? Impact of not defining
serialVersionUID in class and avoiding
InvalidClassException in java
www.javamadesoeasy.com /2015/02/impact-of-not-defining-serialversionuid.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Contents of page :

serialVersionUID
Program 1 - to Serialize Object (without serialVersionUID)>

Modify the Serialized class (but dont serialize the class again)>

Program 2 - to DeSerialize object - program will throw InvalidClassException>


Program 3 - to Serialize Object (with serialVersionUID)>

Modify the Serialized class (but dont serialize the class again)>

Program 4 - to DeSerialize object - Object will be DeSerialized successfully (without InvalidClassException)


>
SUMMARY

serialVersionUID is used for version control of object.


If we dont define serialVersionUID in the class, and any modification is made in class, then we wont be able to
deSerialize our class because serialVersionUID generated by java compiler for modified class will be different from
old serialized object. And deserialization process will end up throwing java.io.InvalidClassException (because of
serialVersionUID mismatch)

The serialization at runtime associates with each serializable class a version number, called a serialVersionUID,
which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes
for that object that are compatible with respect to serialization.

We can use eclipse to generate serialVersionUID for our class (as done in below snapshot)

1/9
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 dont 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 doesnt 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.

Lets discuss this interesting topic in detail with programs-

First we will serialize a class (class which implements Serialization, but we havent declared SerialVersionUID)

Program 1 - to Serialize Object (without serialVersionUID)>

2/9
package serDeser4AddSUID;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Employee implements Serializable {

//we havent declared SerialVersionUId


private Integer id;
private String name;

public Employee(Integer id, String name) {


this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee(1, "amy");
Employee object2 = new Employee(2, "ankit");
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
oout.writeObject(object2);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
*/

Then modify class by adding one field in class, but ensure that you dont run the Serialization process again.

Modify the Serialized class (but dont serialize the class again)>

3/9
class Employee implements Serializable {

private Integer id;


private String name;
private String addedField;
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}

Now, we have added addedField in class which was already Serialized, lets see in absence of SerialVersionUID
whether we will be able to DeSerialize our class or not.

Program 2 - to DeSerialize object - program will throw InvalidClassException>

4/9
package serDeser4AddSUID;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
public class DeSerializeEmployee {

public static void main(String[] args){


try{
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);

System.out.println("DeSerialization process has started, displaying employee objects..." );


Employee emp;
while( (emp=(Employee)oin.readObject())!=null ){
System.out.println(emp);
}
fin.close();
oin.close();

}catch(IOException | ClassNotFoundException e){


e.printStackTrace();
}

System.out.println("Object deSerialization completed.");

}
}
/*OUTPUT
DeSerialization process has started, displaying employee objects...
java.io.InvalidClassException: serDeser4AddSUID.Employee; local class incompatible: stream classdesc
serialVersionUID = 4822384361417160410, local class serialVersionUID = 5590647880449995492
Object deSerialization completed.
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at serDeser4AddSUID.DeSerializeEmployee.main(DeSerializeEmployee.java:18)
*/

DeSerialization process has ended up throwing InvalidClassException.

Now, lets see what will happen when we declare serialVersionUID in Serializable class.

Program 3 - to Serialize Object (with serialVersionUID)>

5/9
package serDeser4AddSUID;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;
private String name;

public Employee(Integer id, String name) {


this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee(1, "amy");
Employee object2 = new Employee(2, "ankit");
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
oout.writeObject(object2);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException ioe) {


ioe.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
*/

Then modify class by adding one field in class, but ensure that you dont run the Serialization process again.

Modify the Serialized class (but dont serialize the class again)>

6/9
class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;
private String name;
private String addedField;
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}

Now, we have added addedField in class which was already Serialized, lets see in presence of SerialVersionUID
whether we will be able to DeSerialize our class or not.

Program 4 - to DeSerialize object - Object will be DeSerialized successfully (without InvalidClassException) >

7/9
package serDeser4AddSUID;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
public class DeSerializeEmployee {

public static void main(String[] args){


try{
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);

System.out.println("DeSerialization process has started, displaying employee objects..." );


Employee emp;
while( (emp=(Employee)oin.readObject())!=null ){
System.out.println(emp);
}
fin.close();
oin.close();

}catch(IOException | ClassNotFoundException e){


//e.printStackTrace();
}

System.out.println("Object deSerialization completed.");

}
}
/*OUTPUT
DeSerialization process has started, displaying employee objects...
Employee [id=1, name=amy]
Employee [id=2, name=ankit]
Object deSerialization completed.
*/

DeSerialization process has ended up successfully.

SUMMARY>

Deserialize class ( class has been modified after Serialization and also class doesnt declare SerialVersionUID)
>Serialize a class (class which implements Serialization, but dont declare SerialVersionUID)

>Then modify class by adding one field in class, but ensure that you dont run the Serialization process again.

>DeSerialization process will end up throwing InvalidClassException.

Deserialize class ( class has been modified after Serialization and also class declare SerialVersionUID)
>Now, lets see what will happen when we declare serialVersionUID in Serializable class.

8/9
>Then modify class by adding one field in class, but ensure that you dont run the Serialization process again.

>DeSerialization process will end successfully.

9/9
Is constructor of class called during DeSerialization
process in java
www.javamadesoeasy.com /2015/02/is-constructor-of-class-called-during.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

It depends on whether our object has implemented Serializable or Externalizable.

If Serializable has been implemented - constructor is not called during DeSerialization process.

But, if Externalizable has been implemented - constructor is called during DeSerialization process.

Full Program/SourceCode to show that If Serializable has been implemented - constructor is not called during
DeSerialization process.

package SerDeser7SerConsCheck;
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;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;

public Employee(){
System.out.println("No-arg constructor called");
}

public Employee(Integer id) {


System.out.println("1-arg constructor called");
this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
}
public class SerializeConstructorCheck {
public static void main(String[] args) {
1/4
Employee object1 = new Employee(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying employee objects..." );
Employee emp=(Employee)oin.readObject();
System.out.println(emp);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}
/*OUTPUT
1-arg constructor called
Serialization process has started, serializing employee objects...
Object Serialization completed.
DeSerialization process has started, displaying employee objects...
Employee [id=8]
Object DeSerialization completed.
*/

If, we note output, constructor is not called during DeSerialization process.

Full Program/SourceCode to show that if Externalizable has been implemented - constructor is called during
DeSerialization process.
>

package SerDeser7ExtConsCheck;
import java.io.Externalizable;
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;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Employee implements Externalizable {

2/4
private static final long serialVersionUID = 1L;
private Integer id;

public Employee(){
System.out.println("No-arg constructor called");
}

public Employee(Integer id) {


System.out.println("1-arg constructor called");
this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
/*
* define how Serialization process will write objects.
*/
@Override
public void writeExternal(ObjectOutput oo) throws IOException {
oo.writeInt(id);
}

/*
* define how deSerialization process will read objects.
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.id=in.readInt();
}
}
public class ExternalizableConstructorCheck {
public static void main(String[] args) {
Employee object1 = new Employee(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying employee objects..." );
Employee emp=(Employee)oin.readObject();
System.out.println(emp);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
3/4
}
}
/*OUTPUT
1-arg constructor called
Serialization process has started, serializing employee objects...
Object Serialization completed.
DeSerialization process has started, displaying employee objects...
No-arg constructor called
Employee [id=8]
Object DeSerialization completed.
*/

If, we note output, constructor is called during DeSerialization process.

4/4
Avoid Deserialization process from creating another
instance of Singleton class in java
www.javamadesoeasy.com /2015/02/avoid-deserialization-process-creating.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

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.

private Object readResolve()


throws ObjectStreamException {
return INSTANCE;
}

Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :

private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{


ois.defaultReadObject();
synchronized (SingletonClass.class) {
if (INSTANCE == null) {
INSTANCE = this;
}
}
}

Full Program/SourceCode to avoid Deserialization process creating another instance of Singleton class>

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.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


public class SingletonClass implements Serializable{
1/3
private static final long serialVersionUID = 1L;
private static SingletonClass INSTANCE = null;
//method returns instance of Singleton class.
public static SingletonClass getInstance() {
if (INSTANCE == null) {
synchronized (SingletonClass.class) {
INSTANCE = new SingletonClass();
}
}
return INSTANCE;
}
//constructor
private SingletonClass() {}
/**
*customize Serialization process.
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
System.out.println("in readObject()");
ois.defaultReadObject();
synchronized (SingletonClass.class) {
if (INSTANCE == null) {
INSTANCE = this;
}
}
}
/**
* Method ensures that we don't break singleton pattern during DeSerialization process- method must not be
called other than DeSerialization time.
*/
private Object readResolve() throws ObjectStreamException {
System.out.println("in readResolve()");
return INSTANCE;
}
public static void main(String[] args) throws Throwable {
System.out.println("Are objects same before serialization : "+ (getInstance() == getInstance()) );
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started...");
oout.writeObject(getInstance());
fout.close();
oout.close();
System.out.println("Object Serialization completed.");
//DeSerialization process >>>>>>>.

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started...");
SingletonClass deSerializedObj = (SingletonClass)oin.readObject();
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");
System.out.println("Are objects same after serialization : "+ (deSerializedObj == getInstance()) );

}
}
/*OUTPUT
Are objects same before serialization : true
Serialization process has started...
2/3
Object Serialization completed.
DeSerialization process has started...
in readObject()
in readResolve()
Object DeSerialization completed.
Are objects same after serialization : true
*/

If we note output, objects are same before and after DeSerialization. So, we have succeeded in not to break
Singleton pattern during DeSerialization process.

Though, multiple instances of Singleton may exist using the above code. However, only one will be referenced at
time (others will be eligible for garbage collection).

3/3
Is constructor of super class called during DeSerialization
process of sub class in java
www.javamadesoeasy.com /2015/02/is-constructor-of-super-class-called.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

It is depends on whether our superclass has implemented Serializable or not.

If superclass has implemented Serializable - constructor is not called during DeSerialization process.

If superclass has not implemented Serializable - constructor is called during DeSerialization process.

Full Program/SourceCode to show that If superclass has implemented Serializable - constructor is not called during
DeSerialization process.

package SerDeser9SuperConsCheck;
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;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Super implements Serializable{
private static final long serialVersionUID = 1L;
public Super(){
System.out.println("No-arg constructor of Super class");
}
}
class Sub extends Super { //it automatically implements Serializable (because it's subclass implements
Serializable).

private static final long serialVersionUID = 1L;


private Integer id;

public Sub(){
System.out.println("No-arg constructor of sub class" );
}

public Sub(Integer id) {


System.out.println("1-arg constructor sub class");
this.id = id;
}
@Override
public String toString() {
1/4
return "Employee [id=" + id + "]";
}
}
public class SerializeDeser {
public static void main(String[] args) {
Sub object1 = new Sub(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying objects..." );
Sub subObj=(Sub)oin.readObject();
System.out.println(subObj);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}
/*OUTPUT
No-arg constructor of Super class
1-arg constructor sub class
Serialization process has started, serializing objects...
Object Serialization completed.
DeSerialization process has started, displaying objects...
Employee [id=8]
Object DeSerialization completed.
*/

If we note output, superclass has implemented Serializable and its constructor is not called during DeSerialization
process.

Full Program/SourceCode to show that If superclass has not implemented Serializable - constructor is called during
DeSerialization process.
>

package SerDeser9SuperConsCheck;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
2/4
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Super {
public Super(){
System.out.println("No-arg constructor of Super class");
}
}
class Sub extends Super implements Serializable{ //it automatically implements Serializable (because it's
subclass implements Serializable).

private static final long serialVersionUID = 1L;


private Integer id;

public Sub(){
System.out.println("No-arg constructor of sub class" );
}

public Sub(Integer id) {


System.out.println("1-arg constructor sub class");
this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
}
public class SerializeDeser {
public static void main(String[] args) {
Sub object1 = new Sub(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying objects..." );
Sub subObj=(Sub)oin.readObject();
System.out.println(subObj);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
3/4
}
/*OUTPUT
No-arg constructor of Super class
1-arg constructor sub class
Serialization process has started, serializing objects...
Object Serialization completed.
DeSerialization process has started, displaying objects...
No-arg constructor of Super class
Employee [id=8]
Object DeSerialization completed.
*/

If we note output, superclass has not implemented Serializable and its constructor is called during DeSerialization
process.

4/4
Can you Serialize Singleton class such that object returned
by Deserialization process is in same state as it was during
Serialization time in java
www.javamadesoeasy.com /2015/02/can-you-serialize-singleton-class-such.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

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)?

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.

private Object readResolve()


throws ObjectStreamException {
return INSTANCE;
}

Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :

private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{


ois.defaultReadObject();
synchronized (SingletonClass.class) {
if (INSTANCE == null) {
INSTANCE = this;
}
}
}

Full Program/SourceCode to Serialize Singleton class such that object returned by Deserialization process is in
same state as it was during Serialization time>

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;
1/3
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


public class SingletonClass implements Serializable {
private static final long serialVersionUID = 1L;
private static SingletonClass INSTANCE = new SingletonClass();
private int x;
@Override
public String toString() {
return "SingletonClass [x=" + x + "]";
}
//method returns INSTANCE of Singleton class.
public static SingletonClass getInstance() {
return INSTANCE;
}
//constructor
private SingletonClass() {}
/**
*customize Serialization process.
*/
private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException {
System.out.println("in readObject()");
ois.defaultReadObject();
INSTANCE = this; //rather than creating new instance, assign current object to INSTANCE
}
/**
* Method ensures that we don't impact state of object in which it was Serialized.
*/
private Object readResolve() {
System.out.println("in readResolve()");
return INSTANCE; //return INSTANCE.
}
public static void main(String[] args) throws Throwable {
SingletonClass object1 = SingletonClass.getInstance();
object1.x = 22;
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(getInstance());
System.out.println("Object state at time of Serialization : "+getInstance());
fout.close();
oout.close();
System.out.println("Object Serialization completed.");
object1.x = 33; // modified after serialization (but it's not going to change state of object in which it was
Serialized, as modification is made after serialization)
System.out.println("Object state modified after Serialization : "+getInstance());

//DeSerialization process >>>>>>>.

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying objects..." );
oin.readObject();
System.out.println("Object state after DeSerialization : "+getInstance()); //It's showing value of x as 22 not
33 (i.e. state in which object was serialized), although x was changed to 33 after serialization.
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

2/3
}
}
/*OUTPUT
Serialization process has started, serializing objects...
Object state at time of Serialization : SingletonClass [x=22]
Object Serialization completed.
Object state modified after Serialization : SingletonClass [x=33]
DeSerialization process has started, displaying objects...
in readObject()
in readResolve()
Object state after DeSerialization : SingletonClass [x=22]
Object DeSerialization completed.
*/

value of x in Object at time of Serialization was 22


value of x in Object was modified after Serialization to 33.
value of x during DeSerialization was 22 (i.e. we were successfully able to get the state of object in which it was
Serialized)

Practically : Where it could be handy to serialize/save state of Singleton class?


Saving laptops state can be handy, daily eod we need to shut it down, but rather than shutting it down hibernate
(save state of laptop) is better option because it enables us to resume at same point where we leaved it, like wise
serializing singleton OR saving state of Singleton can be very handy.

3/3
Are primitive types part of serialization process in java
www.javamadesoeasy.com /2015/02/are-primitive-types-part-of.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Yes, primitive types are part of serialization process. Lets create a program to prove our point.

Full Program/SourceCode to show that primitive types are also part of Serialization>

package serDeser5PrimitiveTypes;
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;
class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private int id;

public Employee(int id) {


this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


public class SerializePrimitiveTypes {
public static void main(String[] args) {
Employee object1 = new Employee(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");
1/2
//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying employee objects..." );
Employee emp=(Employee)oin.readObject();
System.out.println(emp);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
DeSerialization process has started, displaying employee objects...
Employee [id=8]
Object DeSerialization completed.
*/

If we note output, primitive type int was part of Serialization.

2/2
What values will int and Integer will be initialized to during
DeSerialization process if they were not part of Serialization
in java
www.javamadesoeasy.com /2015/02/what-values-will-int-and-integer-will.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

int will be initialized to 0 and Integer will be initialized to null during DeSerialization (if they were not part of
Serialization process).

Full Program/SourceCode to show that int is initialized to 0 and Integer is initialized to null during DeSerialization (if
they were not part of Serialization process) >

package SerDeser8intIntegerInitialized;
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;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private int idInt;
private Integer idInteger;
private String name;

public Employee(String name) {


this.name = name;
}
@Override
public String toString() {
return "Employee [idInt=" + idInt + ", idInteger=" + idInteger
+ ", name=" + name + "]";
}
private void writeObject(ObjectOutputStream os) throws IOException {
System.out.println("In, writeObject() method.");
1/3
os.writeObject(this.name);

/*
* define how deSerialization process will read objects.
*/
private void readObject(ObjectInputStream ois) {
System.out.println("In, readObject() method." );
try {
name=(String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class IntIntegerValueDuringDeSerialization {
public static void main(String[] args) {
Employee object1 = new Employee("ankit");
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects..." );
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying employee
objects...");
Employee emp=(Employee)oin.readObject();
System.out.println(emp);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
DeSerialization process has started, displaying employee objects...
Employee [idInt=0, idInteger=null, name=ankit]
Object DeSerialization completed.
*/

If we note output, int was be initialized to 0 and Integer was initialized to null.

2/3
3/3
Can list, set and maps be Serialized and DeSerialized in java
www.javamadesoeasy.com /2015/02/can-list-set-and-maps-be-serialized-and.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

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.

Full Program/SourceCode to show list, set and maps are Serializable and DeSerializable objects>

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;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


class MyClass implements Serializable {

private static final long serialVersionUID = 1L;


private List<Integer> list;
private Set<Integer> set;
private Map<Integer,Integer> map;

public MyClass(List<Integer> list, Set<Integer> set,


Map<Integer, Integer> map) {
super();
this.list = list;
this.set = set;
this.map = map;
}
@Override
public String toString() {
1/3
return "MyClass [list=" + list + ", set=" + set + ", map=" + map + "]";
}

}
public class SerializeEmployee {
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
list.add(2);
list.add(3);
Set<Integer> set=new HashSet<Integer>();
set.add(4);
set.add(5);
Map<Integer, Integer> map=new HashMap<Integer,Integer>();
map.put(6, 34);
map.put(7, 35);

MyClass object1 = new MyClass(list,set,map);


try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying objects..." );
MyClass object=(MyClass)oin.readObject();
System.out.println(object);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing objects...
Object Serialization completed.
DeSerialization process has started, dispalying objects...
MyClass [list=[2, 3], set=[4, 5], map={6=34, 7=35}]
Object DeSerialization completed.
*/

If we note output, we were successfully able to Serialize and DeSerialize list, set and map objects.

2/3
3/3
Significance of using Static and Transient member variables
- Static and Transient are not serialized in java
www.javamadesoeasy.com /2015/06/significance-of-using-static-and.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Why static member variables are not part of java serialization process ?
Serialization is applicable on objects or primitive data types only, but static members are class level variables,
therefore, different objects 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 wont be in sync with other serialized objects
value.

What is significance of transient variables?


Serialization is not applicable on transient variables (it helps in saving time and space during Serialization process),
we must mark all rarely used variables as transient. We can initialize transient variables during deSerialization by
customizing deSerialization process.

How can you avoid certain member variables of class from getting Serialized?
Mark member variables as static or transient, and those member variables will no more be a part of Serialization.

1/1
compatible and incompatible changes in Serialization and
deSerialization process in java
www.javamadesoeasy.com /2015/06/compatible-and-incompatible-changes-in.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Compatible Changes :
Compatible changes are those changes which does not affect deSerialization process even if class was updated
after being serialized (provided serialVersionUID has been declared)

Adding new fields - We can add new member variables in class.


Adding writeObject()/readObject() methods - We may add these methods to customize serialization process.
Removing writeObject()/readObject() methods - We may remove these methods and then default
customization process will be used.
Changing access modifier of a field - The change to access modifiers i.e. public, default, protected, and
private have no effect on the ability of serialization to assign values to the fields.
Changing a field from static to non static OR changing transient filed to non transient field . - its like addition of
fields.

InCompatible Changes :
InCompatible changes are those changes which affect deSerialization process if class was updated after being
serialized (provided serialVersionUID has been declared)

Deletion of fields. (http://stackoverflow.com/questions/16261383/delete-field-from-old-java-class-


implementing-serializable)
Changing a nonstatic field to static or non transient field to transient field. - its 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.

1/1
Deep copy in java using Serialization and Deserialization
www.javamadesoeasy.com /2015/05/deep-copy-in-java-using-serialization.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

Hi! in this post we will deep copy object using serialization and deserialization process.

Also Read : Serialize and DeSerialize object by implementing Externalizable interface- override writeExternal() and
readExternal() methods

Lets say we want to deep copy emp object using serialization.

In serialization and deserialization process, different object is created after deserialization ( i.e. deSerializedEmp is
created from emp) , also member variables starts referring to different objects (i.e. name and map).

Program for deep copy using Serialization and Deserialization >

package clone;
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;

1/3
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private String name;
private Map<Integer,Integer> map;

public Employee(String name,Map<Integer,Integer> map) {


this.name = name;
this.map=map;
}
@Override
public String toString() {
return "Employee [name=" + name + "]";
}
public String getName() {
return name;
}
public Map<Integer, Integer> getMap() {
return map;
}
}
/**
* Author : AnkitMittal Copyright (c)- javaMadeSoEasy.com
* Main class
*/
public class CloneUsingSerialization {
public static void main(String[] args) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(1, 11);

Employee emp = new Employee("ankit",map);


try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, "
+ "serializing employee object...");
oout.writeObject(emp);
fout.close();
oout.close();
System.out.println("employee Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, "
+ "deSerializing employee object...");
Employee deSerializedEmp=(Employee)oin.readObject();
fin.close();
oin.close();
System.out.println("employee DeSerialization completed.");

System.out.println(emp==deSerializedEmp); //false
System.out.println(emp.getName()==deSerializedEmp.getName()); //false
2/3
System.out.println(emp.getMap()==deSerializedEmp.getMap()); //false

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing employee objects...
Object Serialization completed.
DeSerialization process has started, displaying employee objects...
Object DeSerialization completed.
false
false
false
*/

3/3
If member of class does not implement Serializable interface
- than NotSerializableException is thrown in java.
www.javamadesoeasy.com /2015/02/if-member-of-class-does-not-implement.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

If any of the member does not implement Serializable than NotSerializableException is thrown.

We will use MyClass as a member variable of Serializable class.

Full Program/SourceCode to show that if any of the member does not implement Serializable than
NotSerializableException is thrown>

1/3
package SerDeser10memberNotSer;
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 {}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/


class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;
private MyClass myClass ;

public Employee(Integer id) {


this.id = id;
myClass=new MyClass();
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
}
public class SerializeDeser {
public static void main(String[] args) {
Employee object1 = new Employee(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
System.out.println("Object Serialization completed.");
fout.close();
oout.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing objects...
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.java:42)
*/

If we note output, myClass didnt implemented Serializable interface thats why Serialization process has thrown
2/3
NotSerializableException.

How to avoid NotSerializableException?


We got to ensure that during Serialization all the members of class implements Serializable.

3/3
Can subclass avoid Serialization if its superClass has
implemented Serialization interface in java
www.javamadesoeasy.com /2015/02/can-subclass-avoid-serialization-if-its.html

You are here : Home / Core Java Tutorials / Serialization And Deserialization Tutorial in java

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");
}

Full Program/SourceCode to show how subclass can avoid Serialization if its superClass has implemented
Serialization interface>

package SerDeser11throwNotSerExc;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Super implements Serializable{
private static final long serialVersionUID = 1L;
}
class Sub extends Super {

private static final long serialVersionUID = 1L;


private Integer id;

public Sub(Integer id) {


this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}

/*
* define how Serialization process will write objects.
1/2
*/
private void writeObject(ObjectOutputStream os) throws NotSerializableException {
throw new NotSerializableException("This class cannot be Serialized");
}

}
public class SerializeDeserialize {
public static void main(String[] args) {
Sub object1 = new Sub(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
fout.close();
oout.close();
System.out.println("Object Serialization completed.");

} catch (IOException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
Serialization process has started, serializing objects...
java.io.NotSerializableException: This class cannot be Serialized
at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(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 SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51)
*/

If we note output, subclass was Serializable (as subclass always inherits all features from its parent class ), for
avoiding Serialization in sub-class we defined writeObject() method and throwed NotSerializableException() from
there.

2/2
Serialization - Top 25 interview questions and answers in
java for fresher and experienced(detailed explanation with
programs)
www.javamadesoeasy.com /2015/02/serialization-top-25-interview.html

You are here : Home / Core Java Tutorials / Java Interview Questions and answers

Java Serialization is one the most important topic when it comes to interviews,
developers are frequently using Serialization in their projects, interviewers are interested
in knowing whether interviewees know about Serialization in depth or not, whether they
can customize Serialization process or not and lot more. I will be covering all the classy
questions which could be framed around Serialization and provide you with program for
each and every question.

Question 1. What is Serialization in java?


Answer. Lets start by understanding what is Serialization, its most basic question which you will have to answer
almost in each and every java interview. Serialization is process of converting object into byte stream.
Serialized object (byte stream) can be:
>Transferred over network.
>Persisted/saved into file.
>Persisted/saved into database.
Once, object have have been transferred over network or persisted in file or in database, we could deserialize the
object and retain its state as it is in which it was serialized.

Question 2. How do we Serialize object, write a program to serialize and deSerialize object and persist it in file
(Important)?
Answer. You must be able to write Serialization code to impress interviewer. In order to serialize object our class
needs to implement java.io.Serializable interface. Serializable interface is Marker interface i.e. it does not have any
methods of its own, but it tells Jvm that object has to converted into byte stream .

SERIALIZATION>
Create object of ObjectOutput and give its reference variable name oout and call writeObject() method and pass our
employee object as parameter [oout.writeObject(object1) ]

OutputStream fout = new FileOutputStream("ser.txt");


ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects... ");
oout.writeObject(object1);

DESERIALIZATION>
1/12
Create object of ObjectInput and give its reference variable name oin and call readObject() method
[oin.readObject() ]

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, displaying employee objects..." );
Employee emp;
emp=(Employee)oin.readObject();

Question 3 . Difference between Externalizable and Serialization interface (Important)?


Answer. Here comes the time to impress interviewer by differentiating Serializable and Externalizable use.

SERIALIZABLE EXTERNALIZABLE

Methods It is a marker interface it doesnt have Its not a marker interface.


any method. It has methods called writeExternal() and
readExternal()

Default Serialization YES, Serializable provides its own NO, we need to override writeExternal() and
process default serialization process, we just readExternal() for serialization process to
need to implement Serializable happen.
interface.

Customize serialization We can customize default serialization Serialization process is completely customized
process process by defining following methods We need to override Externalizable interfaces
in our class >readObject() and writeExternal() and readExternal() methods.
writeObject()
Note: We are not overriding these
methods, we are defining them in our
class.

Control over It provides less control over Externalizable provides you great control over
Serialization Serialization as its not mandatory to serialization process as it is important to
define readObject() and writeObject() override writeExternal() and readExternal()
methods. methods.

Constructor call during Constructor is not called during Constructor is called during deSerialization.
deSerialization deSerialization.

Question 4. How can you customize Serialization and DeSerialization process when you have implemented
Serializable interface (Important)?
Answer. Here comes the quite challenging question, where you could prove how strong your Serialization concepts
are.We can customize Serialization process by defining writeObject() method & DeSerialization process by defining
readObject() method.

Lets customize Serialization process by defining writeObject() method :

2/12
private void writeObject(ObjectOutputStream os) {
System.out.println("In, writeObject() method.");
try {
os.writeInt(this.id);
os.writeObject(this.name);
} catch (Exception e) {
e.printStackTrace();
}
}

We have serialized id and name manually by writing them in file.

Lets customize DeSerialization process by defining readObject() method :

private void readObject(ObjectInputStream ois) {


System.out.println("In, readObject() method." );
try {
id=ois.readInt();
name=(String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}

We have DeSerialized id and name manually by reading them from file.

Question 5. Wap to explain how can we Serialize and DeSerialize object by implementing Externalizable interface
(Important)?
Answer. For serializing object by implementing Externalizable interface, we need to override writeExternal() and
readExternal() for serialization process to happen.

For Serialization process override writeExternal() method & for DeSerialization process by override readExternal()
method.

Lets customize Serialization process by overriding writeExternal() method :

public void writeExternal(ObjectOutput oo) throws IOException {


System.out.println("in writeExternal()");
oo.writeInt(id);
oo.writeObject(name);
}

We have serialized id and name manually by writing them in file.

Lets customize DeSerialization process by overriding readExternal() method :

3/12
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("in readExternal()");
this.id=in.readInt();
this.name=(String)in.readObject();
}

We have DeSerialized id and name manually by reading them from file.

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.

Question 7. What is serialVersionUID?


Answer. The serialization at runtime associates with each serializable class a version number, called a
serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object
have loaded classes for that object that are compatible with respect to 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).

Question 8. What will be impact of not defining serialVersionUID in class (Important)?


Answer. This is one my favourite question, i am going to discuss it in a very detailed manner. serialVersionUID is
used for version control of object.
If we dont define serialVersionUID in the class, and any modification is made in class, then we wont be able to
deSerialize our class because serialVersionUID generated by java compiler for modified class will be different from
4/12
old serialized object. And deserialization process will end up throwing java.io.InvalidClassException (because of
serialVersionUID mismatch)

Lets frame another question by twisting few words in it.

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 dont 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 doesnt 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.

Lets discuss this interesting topic in detail - Impact of not defining serialVersionUID in class and avoiding
InvalidClassException

Question 9. What are compatible and incompatible changes in Serialization process?


Answer.

Compatible Changes : Compatible changes are those changes which does not affect deSerialization process even
if class was updated after being serialized (provided serialVersionUID has been declared)

Adding new fields - We can add new member variables in class.


Adding writeObject()/readObject() methods - We may add these methods to customize serialization process.
Removing writeObject()/readObject() methods - We may remove these methods and then default
customization process will be used.
Changing access modifier of a field - The change to access modifiers i.e. public, default, protected, and
private have no effect on the ability of serialization to assign values to the fields.
Changing a field from static to non static OR changing transient filed to non transient field . - its like addition of
fields.

InCompatible Changes : InCompatible changes are those changes which affect deSerialization process if class
was updated after being serialized (provided serialVersionUID has been declared)

Deletion of fields.
Changing a nonstatic field to static or non transient field to transient field. - its 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.
5/12
>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 objects 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 wont be in sync with other serialized objects
value.

Question 12. What is significance of transient variables?


Answer. Serialization is not applicable on transient variables (it helps in saving time and space during Serialization
process), we must mark all rarely used variables as transient. We can initialize transient variables during
deSerialization by customizing deSerialization process.

Question 13. What will happen if one the member of class does not implement Serializable interface (Important)?
Answer. 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. Now, lets see a program.

Question 14. What will happen if we have used List, Set and Map as member of class?
Answer. This question which will check your in depth knowledge of Serialization and Java Apis. 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. Now, lets see a program.

Question 15. Is constructor of class called during DeSerialization process?


Answer. This question which will check your in depth knowledge of Serialization and constructor chaining concepts.
It depends on whether our object has implemented Serializable or Externalizable.
If Serializable has been implemented - constructor is not called during DeSerialization process.
But, if Externalizable has been implemented - constructor is called during DeSerialization process.

DETAILED DESCRIPTION : Is constructor of class called during DeSerialization process

Question 16 . Are primitive types part of serialization process?


Answer. Yes, primitive types are part of serialization process. Interviewer tends to check your basic java concepts
over here.

Question 17. Is constructor of super class called during DeSerialization process of subclass (Important)?
Answer. Again your basic java concepts will be tested over here. It is depends on whether our superclass has
implemented Serializable or not.
If superclass has implemented Serializable - constructor is not called during DeSerialization process.
If superclass has not implemented Serializable - constructor is called during DeSerialization process.
6/12
DETAILED DESCRIPTION : Is constructor of super class called during DeSerialization process of sub class

Question 18. 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).

Question 19. How you can avoid Deserialization process creating another instance of Singleton class (Important)?
Answer. This is another classy and very important question which will check your in depth knowledge of
Serialization and Singleton concepts. Ill 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.

private Object readResolve() throws ObjectStreamException {


return INSTANCE;
}

Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :

private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{


ois.defaultReadObject();
synchronized (SingletonClass.class) {
if (INSTANCE == null) {
INSTANCE = this;
}
}
}

DETAILED DESCRIPTION : Avoid Deserialization process creating another instance of Singleton 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)?
Answer. Its 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.

7/12
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}

Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :

private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{


ois.defaultReadObject();
synchronized (SingletonClass.class) {
if (INSTANCE == null) {
INSTANCE = this;
}
}
}

DETAILED DESCRIPTION : Can you Serialize Singleton class such that object returned by Deserialization process
is in same state as it was during Serialization time

Question 21. Purpose of serializing Singleton class OR purpose of saving singleton state?
Answer. Lets take example of our laptop, daily eod we need to shut it down, but rather than shutting it down
hibernate (save state of laptop) is better option because it enables us to resume at same point where we leaved it,
like wise serializing singleton OR saving state of Singleton can be very handy.

Question 22. 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");
}

DETAILED DESCRIPTION : Can subclass avoid Serialization if its superClass has implemented Serialization
interface

You might be given code snippets in interviews and asked to give output -

Question 23. Find output of following code :

8/12
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;
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class MyClass implements Serializable {

private static final long serialVersionUID = 1L;


private List<Integer> list;
private Set<Integer> set;
private Map<Integer,Integer> map;

public MyClass(List<Integer> list, Set<Integer> set,


Map<Integer, Integer> map) {
super();
this.list = list;
this.set = set;
this.map = map;
}
@Override
public String toString() {
return "MyClass [list=" + list + ", set=" + set + ", map=" + map + "]";
}

}
public class SerializeEmployee {
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
list.add(2);
list.add(3);
Set<Integer> set=new HashSet<Integer>();
set.add(4);
set.add(5);
Map<Integer, Integer> map=new HashMap<Integer,Integer>();
map.put(6, 34);
map.put(7, 35);
MyClass object1 = new MyClass(list,set,map);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
fout.close();
oout.close();
9/12
System.out.println("Object Serialization completed.");

//DeSerialization process >

InputStream fin=new FileInputStream("ser.txt");


ObjectInput oin=new ObjectInputStream(fin);
System.out.println("\nDeSerialization process has started, displaying objects..." );
MyClass object=(MyClass)oin.readObject();
System.out.println(object);
fin.close();
oin.close();
System.out.println("Object DeSerialization completed.");

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}

Answer. Here intention of interviewer will be to find out whether you know that list, set and map can be serialized or
not.

/*OUTPUT
Serialization process has started, serializing objects...
Object Serialization completed.
DeSerialization process has started, dispalying objects...
MyClass [list=[2, 3], set=[4, 5], map={6=34, 7=35}]
Object DeSerialization completed.
*/

Question 24. Find output of following code (Important):

10/12
package SerDeser10memberNotSer;
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 {}
/*Author : AnkitMittal Copyright- contents must not be reproduced in any form*/
class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private Integer id;
private MyClass myClass ;

public Employee(Integer id) {


this.id = id;
myClass=new MyClass();
}
@Override
public String toString() {
return "Employee [id=" + id + "]";
}
}
public class SerializeDeser {
public static void main(String[] args) {
Employee object1 = new Employee(8);
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing objects...");
oout.writeObject(object1);
System.out.println("Object Serialization completed.");
fout.close();
oout.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}

Answer. 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
Serialization process has started, serializing objects...
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.java:42)
11/12
*/

12/12

You might also like