Java Serialization and Deserialization Explained: A Practical Guide for Beginners
Have you ever thought about how an object of Java is stored in a file and reused in the future? When an object’s data has to be stored in a file or sent to some other system in an application, what do we do?
Java offers serialization and deserialization techniques that help us to solve these kinds of problems. This concept is useful when working with file handling, distributed systems, caching, and some kind of data transfer.
In this blog post, we will talk about Java serialization and deserialization in easy language with coding and output.
What Is Serialization in Java?
Serialization in Java is defined as the process of converting the state of an object into a stream of bytes.
In simple terms, through serialization we are able to save the data in an object for use in the future.
Consider an example of a student management application. The student object consists of the following details:
• Student ID
• Student name
• Course name
• Marks
To store the state of the object for future use, Java Serialization will allow us to write the object’s data into a file.
Why Do We Need Serialization?
The process of serialization could be useful in cases when we need to:
• Save the state of an object into a file.
• Pass objects between two different Java applications.
• Hold the objects temporarily for later use.
• Few cases of caching and distributed applications.
But, there are numerous ways to store data and serialization is just one of them. There may be cases where some other techniques like databases, JSON, and others can serve you better.
What Is Deserialization in Java?
Deserialization in Java is the opposite of the serialization process. This process involves converting the byte stream into an object.
Let us assume we have stored the state of a student object in a file. Now, we would like to read this file to get the details of the student such as the student’s name, course, and marks.
This is where deserialization comes into play, which will help us recreate the object using the stored information.
The basic process would be as follows:
Java Object -> Serialization -> Byte Stream -> File
File -> Deserialization -> Java Object
How Does Serialization Work in Java?
Serialization and deserialization operations can be done using classes that are provided in java.
• Serializable: A marker interface which is used for serializing objects when they are eligible. • ObjectOutputStream: Used for writing objects into an output stream.
• ObjectInputStream: Used for reading objects from an input stream.
• FileOutputStream: Used for writing bytes into a file.
• FileInputStream: Used for reading bytes from a file.
In order to serialize any ordinary Java object, it needs to implement Serializable interface, and the object graph should follow Java serialization. Now let's learn about it practically.
Practical Example: Java Serialization and Deserialization
Create a Java class called Student.java.
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String name;
String course;
double marks;
public Student(int id, String name,
String course, double marks) {
this.id = id;
this.name = name;
this.course = course;
this.marks = marks;
}
public void display() {
System.out.println("Student ID : " + id);
System.out.println("Student Name : " + name);
System.out.println("Course : " + course);
System.out.println("Marks : " + marks);
}
}
Usage of above code lines:
• implements Serializable allows the serialization of the class. • serialVersionUID specifies the version of the serialized class. • Constructor initializes the values of the attributes of the student.
• display() is the method used to display the details of the student.
The interface Serializable does not force us to implement any
Methods. Step 2: Serialization of the Student Object
Create another class known as SerializeDemo.java.
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) {
Student s1 = new Student(
101, "Rahul", "Java", 85.5
);
try(ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("student.ser")))
{
out.writeObject(s1);
System.out.println(
"Student object serialized successfully."
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Student object serialized successfully.
When the above program is executed, Java will create a file known as student.ser in the working directory of the application.
The method used to serialize the object in the file is writeObject().
Step 3: Deserialize the Student Object
Next, we will write another program using the name DeserializeDemo.java.
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeDemo {
public static void main(String[] args) {
try (ObjectInputStream in =
new ObjectInputStream(
new FileInputStream("student.ser"))) {
Student s =
(Student) in.readObject();
System.out.println(
"Student object deserialized successfully." );
s.display();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Expected output:
Student object deserialized successfully.
Student ID: 101
Student Name: Rahul
Course: Java
Marks: 85.5
The readObject() method will deserialize the object from its serialized form. Here, we have used typecasting since the return type of the readObject() method is Object.
Note: Execute the SerializeDemo class before executing this program to make sure that the file exists.
What Is the Serializable Interface?
A serializable interface is a very important feature in Java serialization.
This interface is part of the java.io package, and it’s a marker interface.
A marker interface defines the capability of a class without any method definition.
Example:
import java.io.Serializable;
class Employee implements Serializable {
int id;
String name;
}
The Employee class above implements the Serializable interface, making the state of its object Serializable.
If a class does not implement the Serializable interface, any attempt to serialize its objects will throw a NotSerializableException.
What Is serialVersionUID in Java?
The serial version UID is a version identifier used in the process of serializing java objects.
Imagine the scenario where the object is serialized in the current day, and then the class of that object is modified before the process of deserializing the stored object.
The serial version UID is used by java to verify whether the serialized data is compatible with the class definition.The process of deserialization may fail due to non-existence of compatibility and causing the InvalidClassException.
Example:
private static final long serialVersionUID = 1L;
Here the serial version identifier is defined explicitly.
If you decide that your class should support serialization, then you have to provide serialUID. However, maintaining the same value doesn’t imply compatibility of all changes to the class.
What Is the transient Keyword in Java Serialization?
There may be situations when we do not want to serialize a particular instance field.
In Java, there is the transient keyword for this.
Here is an example:
import java.io.Serializable;
class User implements Serializable {
int id;
String username;
transient String password;
}
Here, the variable password is marked transient.
When performing default serialization, the value of this field will not be serialized. After deserialization, this field will have a default value. In case of reference type like String, the default value will be null.
Transient keyword may come in handy when you are trying to omit certain fields from serialization.
The problem is that transient keyword does not ensure the safety of your data.
Difference Between Serialization and Deserialization
Serialization Deserialization
The process of converting object state into a byte stream. The process of reconstructing an object from a byte stream. Uses ObjectOutputStream. Uses ObjectInputStream.
Uses writeObject() method mostly. Uses readObject() method mostly. Can store the serialized objects in a file. Can read the serialized objects from a file.
Serialization and deserialization go hand-in-hand in case the application needs to store and fetch the state of the object.
Common Errors in Java Serialization
There could be a number of difficulties that a beginner may encounter while using serialization. 1. NotSerializableException
This problem may occur because the object intended for serialization does not fulfill all the conditions required for serialization.
Solution: See if the class implementing Serializable is there and if the object fields of the class are either transient or serializable.
2. FileNotFoundException
This problem may occur in case the file does not exist or the file path entered is wrong.
Solution: Check the file path and ensure that serialization has been done before deserialization.
3. InvalidClassException
This problem may arise in case the serial version identifier of the stored data and the class are not the same.
Solution: Check the value of serialVersionUID. 4. ClassNotFoundException
This exception may be raised in case the class required to rebuild the object is not found.
Solution: Ensure that the necessary class is present in the application classpath.
Best Practices for Java Serialization
Follow these practices when working with serialization:
•These are the best practices to follow when dealing with serialization:
• Only apply serialization if it is appropriate for your application.
• Mark the members as transient, which you don't want to serialize by default.
• Be ready to deal with file and serialization exceptions.
• Don’t deserialize data from an untrusted source. Java native deserialization may expose your application to severe security issues.
• JSON could be another good option.
Real-World Uses of Serialization
There can be different uses for Java serialization.
Persisting objects: The application can serialize an object in order to restore its state later on.
Distributed computing: In certain Java systems, the process of serialization is used to transfer the representation of objects between system components.
Caching: Certain caching solutions can serialize objects that will be stored outside the scope of the application’s memory space.
Serializing objects related to the sessions in certain Java application servers or frameworks: It is done in certain configuration setups.
Conclusion
Java Serialization and Deserialization provide a method of saving the state of an object as a byte stream and rebuilding that object.
In our tutorial on practical implementation, we covered the Serializable interface, ObjectOutputStream, ObjectInputStream, serialVersionUID, and the transient keyword. We also demonstrated saving an object into a file and then restoring it from a file using Java code.
For beginners, the most effective way of learning these concepts is to try running both programs and examining the resulting file while changing various attributes.
Learning these concepts results in building a stronger background in handling files and objects in Java. However, one also needs to be aware of security restrictions of native serialization and choose the right approach to data storage for each application.
Author:
Aarti Choudhary
Related Links:
Resume Tips For Software Developers
Do visit our channel to know more: SevenMentor
Aarti Choudhary
Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.