What is Serialization in Java?

What is Serialization in Java?

9 mins read102 Views Comment
Updated on Oct 3, 2023 11:59 IST

Greetings, Java programmers, if you are facing a problem understanding Serialization in Java, then you have just landed in the right place. Here you will understand the core concept of Serialization and Deserialization in Java.

2023_07_Untitled-design-4.jpg

Serialization in Java is a process that allows objects to be converted into a stream of bytes, which can be easily stored, transmitted, or reconstructed later. It facilitates the persistence of object data and enables communication between different Java applications. The serialized data can be saved in files, sent over networks, or stored in databases, making it a crucial mechanism for data exchange and storage in Java programs.

Let’s understand more about it and related concepts.

Check out: Online Java Courses and Certifications

Table of Content

What is Serialization in Java?

Serialization in Java is converting an object into a sequence of bytes that can be persisted to a disk or database or transmitted over a network. All of the information about the object is contained in the byte stream.

Deserialization in Java is the opposite process, where we convert the sequence of bytes streams into an object. An in-depth discussion of this will be provided later in the article.

If a Java object’s class or any of its subclasses implements java.io.Serialzable then we can say it is serializable, or if it uses its subinterface java.io.Externalizable interface, then we can say it is serializable.

The entire process of serialization is JVM (Java Virtual Machine) independent. It means an object can be serialized on one platform and deserialized on another.

It’s important to note that not all objects can be serialized in Java. Some objects, such as threads, sockets, and file handles, cannot be serialized. Additionally, the serialization and deserialization processes can have security implications, so it’s important to be careful when working with serialized objects from untrusted sources.

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
350 hours
Free
6 months
– / –
4 months
– / –
– / –
– / –
1 month
40 K
7 weeks
7.8 K
3 months
8.47 K
2 months
7 K
6 months
4 K
2 months

Why do we use Serialization?

To understand Serialization in Java, we must first understand why it is used.

Let’s take an example to understand:-

In Java, to run a program, first, we create a class, and then we create functions or objects to fulfil our requirements for the program. We can execute a program in Java without creating an object, but in this case, we will assume that we have created an object for our program.

Now, when our program executes with an object, it takes some disk storage to run the program, but after execution, the whole disk storage got destroyed by itself. As we know, Java has a garbage collector by default. It clears the memory, and if we have to execute the same object again, it recreates the disk memory for the object. To overcome this problem, we use Serialization, convert the data into a byte stream, and store that on disk storage.

Benefits of Serialization

Serialization has several benefits, so let us check these out,

I. Persistence: Serialization makes it simple to store objects in a file or in a database and retrieve them later, which makes it easy to implement persistent storage in applications. This allows the application to store the object for long-term purposes, such as enterprise applications and data-intensive systems.

II. Interoperability: As we read above, Serialization is JVM-independent, which means it is a platform-independent way of transmitting objects between different systems. This is because serialized objects are represented as a stream of bytes, which can be transmitted over a network and then deserialized on the receiving end to create an identical object.

III. Security: Serialization also gives our program more security as it can be used to implement secure communication between different networks.

IV. Performance & Flexibility: As we read above it helps us to reuse the objects we need repeatedly and save time to run programs. It also gives us flexibility in the development and design of Java applications.

Overall, Java’s serialization feature is strong and has several advantages, including enhanced performance, security, and flexibility.

History of Java: From Island Origins to Programming Powerhouse
Factorial program in Java 
List of Keywords in Java

Things to keep in mind before Serialization

Before serializing a program, we have to remember some conditions that must be met; otherwise, the program can crash.

I. We can only serialize the objects in Java that implement the Serializable interfaces. If the class does not use a Serializable interface, then a NotSerializableException will be thrown at runtime while attempting to serialize an instance of that class.

II. As we serialize an object or a class, it is stored in a file or storage in binary format. It is important to remember that if any modification happens to that object or class, then the serialized binary format will also change.

III. We must ensure that before serializing any confidential data like passwords, credit card numbers, bank details, etc., it must be encrypted first and then serialized. This will prevent the data from being accessed by any unauthorized person or organization.

IV. We must not serialize the unnecessary data, as it would take up extra storage on the disk, and the users would face performance issues.

By keeping these items in mind, you can ensure that you utilize serialization in your Java programs safely and effectively.

What is the process of serializing an Object?

Now we will understand the process of serializing an object in Java; we need some methods and classes for that.

  1. As we know, we have to implement the java.io.Serialzable in our class.
  2. We must use the writeObject() method of the ObjectOutputStream class for serialization.
  3. These methods throw I/O Exceptions, so we need to use try-catch blocks to prevent the exceptions.

Example of Serialization in Java with Code and Output.

Here we will create an employee class that implements java.io.Serializable and let us serialize an employee object.

 
import java.io.*;
public class Employee implements java.io.Serializable{
public String name;
public String company_name;
public int emp_id;
public static void main(String[] args) {
Employee e1 = new Employee();
e1.name = "Sk Elaf Ahmed";
e1.company_name = "Siksha.com";
e1.emp_id = 1;
try {
FileOutputStream fileOut = new FileOutputStream("F:\\Java Serialization\\test.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e1);
out.close();
fileOut.close();
System.out.println("Our data is serialized and saved in disk storage");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Copy code

Output:

Saved data in the test.txt file

Don’t worry; we’ll understand everything.

First, we created the Employee.java and test.txt files, where our serialized data will be stored.

Now we have imported java.io.* to use every method easily. Now we created the public variables where we will store the employee details. After that, in the main Java function, we will write our code in try-catch as we already know it throws IOExceptions. Now, give value to those variables.

After that, in the try-catch block, we will define the test.txt file location as we want to save the serialized data into that. Providing the exact path is important; otherwise, it throws a runtime error. 

Now we will use the ObjectOutputStream() class and write our object for serialization. Finally, don’t forget to close those classes, or there will be a resource leak.

As you can see in the above image, our object becomes a byte stream, as it is a byte stream we humans can understand so we need deserialization.

By using some other classes, we can easily deserialize our byte stream data.

Master the Concept of Recursion Java
How to Find Reverse of a Number in Java
Check Palindrome in Java Using Different Methods

What is Deserialization in Java?

To understand serialization in depth, we also have to understand what is Deserialization. Don’t worry; we are going to understand it.

Definition: Deserialization is just the opposite process of serialization, where the byte stream is put back into the object. 

During this process, the serialized data is read and used to reconstruct the objects’ state, including their fields and object values.

The readObject() method of an ObjectInputStream object is used for deserialization, and it’s crucial to make sure that the JVM can access the class of the serialized object and that the serialized data is secure.

We shall learn to code deserialization in any other post, as this one is focused on serialization.

Java Serialization with Inheritance(Is-A-Relationship)

As we know, Java supports OOPs(Object Oriented Programming) which means it also supports inheritance.

And serialization in Java supports inheritance, which means that when a subclass is serialized, its superclass will be automatically serialized.

Let’s look at an example:

 
import java.io.*;
import java.io.Serializable;
class Person implements Serializable{
String person_name;
Person(String person_name){
this.person_name = person_name;
}
}
public class Employee2 extends Person {
// Serialization with Inheritance
String emp_company;
int emp_Id;
public Employee2(String person_name, String emp_company, int emp_Id){
super(person_name);
this.emp_company = emp_company;
this.emp_Id = emp_Id;
}
public static void main(String[] args) {
Employee2 e2 = new Employee2("Roshni", "Siksha.com", 2);
try {
FileOutputStream fileOut = new FileOutputStream("F:\\Java Serialization\\test2.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e2);
out.close();
fileOut.close();
System.out.println("Object is serialized using Java Inheritance in test2.txt");
} catch (IOException e) {
e.printStackTrace();;
}
}
}
Copy code

Output:

Saved data into the test2.txt

For better understanding, we used a class called Person, which has a person’s name, and the Employee2 class extends the Person class using the extends keyword. This is how we use inheritance in Java. The Employee2 class also has its own characteristics, just like our previous code, and now it also follows the normal serialization process.

After that, we saw the output, so let us see the saved text now in our test2.txt file.

Java Serialization with Aggregation(Has-A-Relationship):

Here we have to understand that, serialization comes with some conditions, let us see the code first,

Code:

 
import java.io.*;
import java.io.Serializable;
// Serialization in Java with Aggregation
class Details{
String em_email, em_address;
int em_number;
public Details(String em_email, String em_address, int em_number){
this.em_email = em_email;
this.em_address = em_address;
this.em_number = em_number;
}
}
public class Employee3 implements Serializable{
int em_Id;
String em_name;
Details details; // Has-A
public Employee3(int em_Id, String em_name){
this.em_name = em_name;
this.em_Id = em_Id;
}
}
Copy code

As we can see from the code above, the Details class does not implement Serializable and has some data when it is first created. In contrast, the Employee3 class does implement Serializable. So, a NonSerializableException will be raised at runtime if we attempt to execute this code.

Java Transient Keyword

The transient keyword in Java is very important, so it is reserved in Java. Although it can be a complete topic to be discussed, here we will learn it in a simple manner.

We already know our ability to Serialize and Deserialize any desired objects. But if we do not want to serialize a class’s specific data or data sets, we have to add the ‘transient’ keyword before that data.

By doing so, we are able not to serialize the desired data.

SerialVersionUID in Java

At last, we have to know what is SerialVersionUID to understand serialization completely.

A unique identifier must be carried when an item is serialized and deserialized to guarantee that the same object is received both times and not differently. So, here comes the SerialVersionUID, which helps us to identify the different objects.

When an object is serialized, the SerialVersionUID is also written along with the object’s data, as seen in the test.txt file.

So in that process, if the SerialVersionUID does not match, the program will throw an InvalidClassException.

The essay is complete, and we sincerely hope your questions have been answered. Perhaps this will aid in your future Java development.

Contributed by: Elaf Ahmed

FAQs

What is Serialization in Java?

Serialization is a Java process of converting objects into a stream of bytes to facilitate storage, transmission, or sharing of data.

How do I serialize an object in Java?

To serialize an object, implement the Serializable interface, and use ObjectOutputStream to write the object to a file or stream.

What is the purpose of the Serializable interface?

The Serializable interface acts as a marker to indicate that objects of a class can be serialized, ensuring they can be converted to bytes.

How can I control the serialization process in Java?

By implementing custom serialization methods readObject() and writeObject(), developers can have control over how objects are serialized and deserialized.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio