Skip to main content

Serialization in Java

Serialization in Java

In this article, we are going to learn how to accomplish Serialization in java and the importance of serialization. Also, we will learn the reverse of serialization i.e., Deserialization.

What is Serialization in java?

Serialization is a process that is used to convert an object into the stream of bytes so that the stream data bytes can be transferred to any location outside the java like databases, network transmission, files, etc.

Deserialization in java

Deserialization is the reverse of serialization in which the stream of bytes is converted back into an object. This is majorly used to fetch data from databases, read files or received data packets from the network and deserialized into an object within the java memory space.

How to do serialization in java?

To achieve serialization in java, we need to use a marker interface named as Serializable. Serializable interface is the part of the java.io package and If any object needs to be serialized or deserialized then it must implement the Serializable interface.
Note: A Marker interface is an interface that does not add any functionality to the object who implements it but it marks the object which signifies to the JVM that this object is now having some special meaning. Serializable marker interface tells JVM that this object can be serialized or deserialized.
Let's explain this with an example:

Java Serialization Example 1: Serialize a user-defined object into the file system

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

class Book implements Serializable {
    private String name;
    private Integer price;
    private String edition;

    public Book(String name, String edition, Integer price) {
        this.name = name;
        this.price = price;
        this.edition = edition;
    }

    @Override
    public String toString() {
        return "[ name : " + name + ", edition : " + edition + ", " 
                                + "price : " + price + "]";
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        Book javaBook = new Book("Learn Java", "8th", 550);
        Book pythonBook = new Book("Coding in Python", "5th", 750);
        Book dataStructureBook = new Book("Data Structures", "2nd", 400);
        Book databaseBook = new Book("Introduction to Database", "4th", 500);

        try {
            FileOutputStream fileOutputStream = new FileOutputStream("books-file");
            ObjectOutputStream objectOutputStream 
                = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(javaBook);
            objectOutputStream.writeObject(pythonBook);
            objectOutputStream.writeObject(dataStructureBook);
            objectOutputStream.writeObject(databaseBook);
            
            fileOutputStream.close();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}
In the above example, we serialize a few objects of the Book class using the writeObject() method. Run this program and see into your file system, a file named with the "books-file" will be created. Now, learn how to read that file and perform deserialization in java.
To know more, Each-n-every class provided by the Java Collection Framework implements Serializable interface which means any collection (including maps) are subjected to serialization in java.

How to do deserialization in java?

In the last section, we have performed the serialization to store a few books into the file. Now, its time to get back all the data that we have serialized earlier in the file. For deserialization, we need to use the same class which was used at the time of serialization in java, otherwise java.lang.ClassCastException will be raised.

Java Serialization Example 2: De-Serialize all the data from the file

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class SerializationExample {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("books-file");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

            Book book = null;
            while ((book = (Book) objectInputStream.readObject()) != null) {
                System.out.println(book);
            }
            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException  e) {
        }
    }
}
Output
[ name : Learn Java, edition : 8th, price : 550]
[ name : Coding in Python, edition : 5th, price : 750]
[ name : Data Structures, edition : 2nd, price : 400]
[ name : Introduction to Database, edition : 4th, price : 500]

Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…