Serialization
Serialization
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.
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 >
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
serialVersionUID >
Impact of not defining serialVersionUID in class and avoiding InvalidClassException
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
What values will int and Integer will be initialized to during DeSerialization process if they were not part of
Serialization
Significance of using Static and Transient member variables - Static and Transient are not
serialized in java
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) ]
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;
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();
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>
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
If oin.readObject() returns instanceof EofIndicatorClass that means it's EOF , exit while loop and
EOFException will not be thrown.
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 {
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.
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;
/*
* 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.");
}
}
/*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.
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 {
/*
* 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);
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 {
}
}
/*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.
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 {
/*
* 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);
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 {
}
}
/*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
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.
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)>
Modify the Serialized class (but dont serialize the class again)>
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.
First we will serialize a class (class which implements Serialization, but we havent declared 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;
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 {
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.
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 {
}
}
/*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)
*/
Now, lets see what will happen when we declare serialVersionUID in Serializable class.
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 {
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 {
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 {
}
}
/*OUTPUT
DeSerialization process has started, displaying employee objects...
Employee [id=1, name=amy]
Employee [id=2, name=ankit]
Object deSerialization completed.
*/
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.
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.
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
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;
public Employee(){
System.out.println("No-arg constructor called");
}
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");
}
/*
* 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.");
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.
Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :
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;
}
}
/*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
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).
public Sub(){
System.out.println("No-arg constructor of sub class" );
}
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).
public Sub(){
System.out.println("No-arg constructor of sub class" );
}
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.
Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :
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 */
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.
*/
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 {
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;
/*
* 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.");
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;
}
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);
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.
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)
InCompatible Changes :
InCompatible changes are those changes which affect deSerialization process if class was updated after being
serialized (provided serialVersionUID has been declared)
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
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).
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 {
System.out.println(emp==deSerializedEmp); //false
System.out.println(emp.getName()==deSerializedEmp.getName()); //false
2/3
System.out.println(emp.getMap()==deSerializedEmp.getMap()); //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.
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 {}
} 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.
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.
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 {
/*
* 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 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) ]
DESERIALIZATION>
1/12
Create object of ObjectInput and give its reference variable name oin and call readObject() method
[oin.readObject() ]
SERIALIZABLE EXTERNALIZABLE
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.
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();
}
}
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.
3/12
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("in readExternal()");
this.id=in.readInt();
this.name=(String)in.readObject();
}
Question 6. How can you avoid certain member variables of class from getting Serialized?
Answer. Mark member variables as static or transient, and those member variables will no more be a part of
Serialization.
We can use eclipse to generate serialVersionUID for our class (as done in below snapshot)
How to avoid warning The serializable class Employee does not declare a static final serialVersionUID field of type
long ?
Again answer is we can use eclipse to generate serialVersionUID for our class (as mentioned in above screenshot,
click on warning button on left in line 10).
If you have serialized a class & then added few fields in it and then deserialize already serialized version of class,
how can you ensure that you 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
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)
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 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 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.
Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done
below :
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 :
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.
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 -
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 {
}
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.");
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.
*/
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 {
} 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