Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Serialization in Java

Picture this: You freeze a moment in time, like capturing a firefly in a jar. Serialization in Java does something similar—it preserves the essence of objects, encapsulating their state into a byte stream. Think of it as digital cryogenics for your data!  

With Java overshadowing other programming languages in popularity (enjoying more than 63.6% usage among developers), learning about its components is essential and the concept of serialisation is no exception. This blog makes an in-depth exploration into Serialization in Java encompassing its methods, advantages and a wide range of examples.

Table of Contents 

1) What is Serialization in Java?

2) Advantages of Serialization in Java  

3) Serialization Methods in Java  

4) Example of Serialization  

5) Example for Deserialization in Java 

6) Advanced Java Serializations

7) What is the Transient Keyword? 

8) Conclusion  

What is Serialization in Java?

The method of converting the state of any object into a stream of bytes is termed Serialization. In Java, an object can be changed into a stream of static bytes.

What is Serialization?

The generated stream of a byte is multiplatform-based, where the Serialization of objects can be carried out on one platform and Deserialized on another. A Serializable class object can be obtained by implementing the java.io.Serializable interface or its sub-interface, java.io.Externalisable.  

 Fields or methods are absent, so a class does not have to implement them, and that’s why Serializable in Java is a marker interface. An object inside the class needs to be serialized only when this Serializable interface is called to direct to the Java Serialization classes.
 

 Java Programming

 

How Serialization Works in Java?

Serialization in Java converts an object's state into a byte stream for more convenient storage or transmission over a network. The primary purpose of serialization is to persist the state of an object so it can be recreated later.

Here's an example to illustrate how Serialization works in Java:

a) Define a Serializable Class: To serialize an object, the class must use the Serializable interface. This interface doesn't contain any methods, but it signals to the JVM that the class can be serialized.
 

import java.io.serializable;

public class Person implements serializable {   

     private static final long serialVersionUID = 1L; // version control for the serialized class

     private String name;    

     private int age;    

     public Person(String name, int age) {     

            this.name = name;    

            this.age = age;   

  }    

@Override    

public String toString() {        

    return "Person{name='" + name + "', age=" + age + "}";   

  }

}

 

b) Serialize the Object: Use ObjectOutputStream to write the object's state to a file.
 

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

public class SerializeExample {

    public static void main(String[] args) {

        Person person = new Person("John Doe", 30);

        try (FileOutputStream fileOut = new FileOutputStream("person.ser");

             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {

            out.writeObject(person);

            System.out.println("Serialized data is saved in person.ser");

        } catch (IOException i) {

            i.printStackTrace();

        }

    }

}

 

c)    Deserialize the Object: Use ObjectInputStream to read the object's state from the file and recreate the object.

import java.io.FileInputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

public class DeserializeExample {

    public static void main(String[] args) {

        Person person = null;

        try (FileInputStream fileIn = new FileInputStream("person.ser");

             ObjectInputStream in = new ObjectInputStream(fileIn)) {

            person = (Person) in.readObject();

        } catch (IOException | ClassNotFoundException i) {

            i.printStackTrace();

        }

        System.out.println("Deserialized Person:");

        System.out.println(person);

    }

}

 

Output: When you run the SerializeExample class, it will create a file named person.ser containing the serialized data of the Person object. When you run the DeserializeExample class, it will read the data from person.ser and recreate the Person object.
 

Serialized data is saved in person.ser

Deserialized Person:

Person{name='John Doe', age=30}


Advantages of Serialization in Java

Serialization in Java has several advantages, such as:

a) It allows us to persist the state of an object to a file, database, or memory and restore it later when needed.

b) It enables us to communicate objects across a network between different Java applications, such as RMI, JPA, EJB, and JMS technologies.

c) It provides a way to deep copy an object by serializing and deserializing it, creating a replica of the original object.

d) It can be used to create caching objects that are expensive or time-consuming by serializing them once and reusing them multiple times.  

e) It supports inheritance and polymorphism, meaning subclasses and interfaces can be serialized if they implement the serializable interface.

f) It allows us to customise the Serialization process by using methods like writeObject (), readObject (), writeReplace (), and readResolve () to control how the object is serialized and deserialized.

g) It enables us to encrypt and compress the serialized data for security and performance reasons using wrappers like CipherOutputStream and GZIPOutputStream.

h) It facilitates versioning and compatibility of serialized objects by using features like serialVersionUID, serialPersistentFields, and transient and static modifiers.

Serialization Methods in Java 

Four types of methods exist that can be used to perform the Serialization method in Java. These methods are listed below with their function:

Serialization Methods in Java

1) readObject(ObjectInputStream ois): This method will read the object from the stream. 

2) writeObject(ObjectOutputStream oos): This method will write the object to the stream. 

3) Object readResolve(): This method is called after the Deserialization process, and to the caller function the final objects is returned.  

4) Object writeReplace(): This method is called after the Serialization process, and the serialized object is returned to the stream. 

Learn how to make desktop application and important concept of GUI programming with Java by signing up for our Java Swing Development Training now! 

Example of Serialization in Java

Serialization is the process of converting an object into a stream of bytes that can be stored or transmitted. It is useful for saving an object's state or sending it across a network.

To serialize an object in Java, the class of the object must implement the Serializable interface, which is a marker interface that indicates the object can be serialized. The ObjectOutputStream class provides the writeObject() method to write an object to an output stream. The ObjectInputStream class provides the readObject() method to read an object from an input stream.

Here is an example of Serialization in Java:
 

// A class that implements Serializable

class Student implements Serializable {

  int id;

  String name;

  public Student(int id, String name) {

    this.id = id;

    this.name = name;

  }

}

// A class that demonstrates serialization and deserialization

public class SerializationExample {

  public static void main(String[] args) {

    // Create a Student object

    Student s1 = new Student(101, "Alice");

    // Serialize the object and write it to a file

    try {

      FileOutputStream fos = new FileOutputStream("student.ser");

      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(s1);

      oos.close();

      fos.close();

      System.out.println("Object serialized");

    } catch (IOException e) {

      e.printStackTrace();

    }


Output:
 

Object serialized

Id: 101

Name: Alice

 

Deserialization in Java

Deserialization is the process of converting a stream of bytes representing an object into the actual object in memory. It is the reverse operation of Serialization, which is the process of converting an object into a stream of bytes that can be stored or transmitted.

To deserialize an object in Java, the class of the object must implement the Serializable interface, which is a marker interface that indicates the object can be deserialized. The ObjectInputStream class provides the readObject() method to read an object from an input stream. The readObject() method returns an Object type, which needs to be cast to the appropriate class type.
 

Here is an example of Deserialization in Java:

// A class that implements Serializable

class Student implements Serializable {

  int id;

  String name;

  public Student(int id, String name) {

    this.id = id;

    this.name = name;

  }

}

// A class that demonstrates deserialization

public class DeserializationExample {

  public static void main(String[] args) {

    // Deserialize the object and read it from the file

    try {

      FileInputStream fis = new FileInputStream("student.ser");

      ObjectInputStream ois = new ObjectInputStream(fis);

      Student s = (Student) ois.readObject(); // cast to Student type

      ois.close();

      fis.close();

      System.out.println("Object deserialized");

      System.out.println("Id: " + s.id);

      System.out.println("Name: " + s.name);

    } catch (IOException | ClassNotFoundException e) {

      e.printStackTrace();

    }

  }

}

 

Output:
 

Object deserialized

Id: 101

Name: Alice

 

Learn to map Annotations and identify Hibernate Mapping Association by signing up for our Hibernate Training now!

Advanced Java Serializations

Advanced Java Serialization is the process of customising or enhancing the default Serialization mechanism provided by the Java platform. It involves using techniques such as implementing the Externalisable interface, overriding the writeObject and readObject methods, defining the serialVersionUID field, and using the transient keyword.

Serialization in Java with Inheritance

Inheritance is the relationship between a superclass and a subclass, where the subclass inherits the properties and behaviors of the superclass. Serialization with inheritance is when a subclass object is serialized or deserialized, and the superclass may or may not implement the Serializable interface.

There are two cases to consider:

a) If the superclass is serializable, then the subclass is automatically serializable, and all the instance variables of the superclass and the subclass are serialized or deserialized. There is no need for the subclass to implement the Serializable interface explicitly, unless it wants to define its own serialVersionUID or custom Serialization logic.

b) If the superclass is not serializable, then the subclass can still be serializable if it implements the Serializable interface explicitly. However, only the instance variables of the subclass are serialized or deserialized, and the instance variables of the superclass are ignored or initialised with their default values. Also, the no-arg constructor of the superclass is invoked during Deserialization, so the superclass must have a public or protected no-arg constructor.

Here is an example of Java Serialization with Inheritance
 

// A superclass that implements Serializable

class Animal implements Serializable {

  String name;

  public Animal(String name) {

    this.name = name;

  }

}

// A subclass that inherits from Animal

class Dog extends Animal {

  String breed;

  public Dog(String name, String breed) {

    super(name); // call the superclass constructor

    this.breed = breed;

  }

}

// A class that serializes and deserializes a Dog object

public class InheritanceExample {

  public static void main(String[] args) {

    // Create a Dog object

    Dog d1 = new Dog("Rex", "German Shepherd");

    // Serialize the object and write it to a file

    try {

      FileOutputStream fos = new FileOutputStream("dog.ser");

      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(d1);

      oos.close();

      fos.close();

      System.out.println("Object serialized");

    } catch (IOException e) {

      e.printStackTrace();

    }

    // Deserialize the object and read it from the file

    try {

      FileInputStream fis = new FileInputStream("dog.ser");

      ObjectInputStream ois = new ObjectInputStream(fis);

      Dog d2 = (Dog) ois.readObject(); // cast to Dog type

      ois.close();

      fis.close();

      System.out.println("Object deserialized");

      System.out.println("Name: " + d2.name);

      System.out.println("Breed: " + d2.breed);

    } catch (IOException | ClassNotFoundException e) {

      e.printStackTrace();

    }

  }

}

 

Output: 
 

Object serialized

Object deserialized

Name: Rex

Breed: German Shepherd

 

Learn how to develop a web application using Java Programming by signing up for our Web Development Using Java Training now!

Serialization in Java with Aggregation

Aggregation is the relationship between a class and another class that is a part of it, where the class has a reference to the other class. Serialization with aggregation is the scenario where a class object is serialized or deserialized, and the class has a reference to another class that may or may not implement the Serializable interface.

There are two cases to consider:

a) If the referenced class is serializable, then the reference is serialized or deserialized along with the class object. Additionally, all the instance variables of the class and the referenced class are serialized or deserialized. The referenced class does not need to implement the Serializable interface explicitly unless it wants to define its own serialVersionUID or custom serialization logic.

b) If the referenced class is not serializable, then the reference is not serialized or deserialized, and an exception is thrown at runtime. The class object cannot be serialized or deserialized unless the reference is marked as transient, which means it is excluded from the Serialization process.

Here is an example of Java Serialization with aggregation:
 

// A class that implements Serializable

class Address implements Serializable {

  String city;

  String country;

  public Address(String city, String country) {

    this.city = city;

    this.country = country;

  }

}

// A class that has a reference to Address

class Person implements Serializable {

  String name;

  Address address; // aggregation

 

  public Person(String name, Address address) {

    this.name = name;

    this.address = address;

  }

}

// A class that serializes and deserializes a Person object

public class AggregationExample {

  public static void main(String[] args) {

    // Create an Address object

    Address a1 = new Address("London", "UK");

    // Create a Person object

    Person p1 = new Person("Alice", a1);

    // Serialize the object and write it to a file

    try {

      FileOutputStream fos = new FileOutputStream("person.ser");

      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(p1);

      oos.close();

      fos.close();

      System.out.println("Object serialized");

    } catch (IOException e) {

      e.printStackTrace();

    }

    // Deserialize the object and read it from the file

    try {

      FileInputStream fis = new FileInputStream("person.ser");

      ObjectInputStream ois = new ObjectInputStream(fis);

      Person p2 = (Person) ois.readObject(); // cast to Person type

      ois.close();

      fis.close();

      System.out.println("Object deserialized");

      System.out.println("Name: " + p2.name);

      System.out.println("City: " + p2.address.city);

      System.out.println("Country: " + p2.address.country);

    } catch (IOException | ClassNotFoundException e) {

      e.printStackTrace();

    }

  }

}

 

Output: 
 

Object serialized

Object deserialized

Name: Alice

City: London

Country: UK

 

Serialization in Java with Static Data Member

A static data member is a variable that belongs to the class, not any individual instance. All the class instances share it and can be accessed without creating an object. Serialization with static data member is when a class object is serialized or deserialized, and the class has a static data member that may or may not be initialised.

There are two points to remember:

a) A static data member is not serialized or deserialized, because it is not part of the state of the object. It is part of the state of the class, which is not affected by the Serialization process. Therefore, the value of the static data member is not saved or restored during Serialization or Deserialization.

b) A static data member is initialised by the static initialiser block or the static variable declaration, which are executed only once when the class is loaded. Therefore, the value of the static data member depends on when the class is loaded, which may vary depending on the runtime environment. If the class is loaded before serialization, the static data member will have the same value in both the sender and the receiver. If the class is loaded after Serialization, the static data member will have the default value in the receiver.

Here is an example of Java Serialization with Static Data Member:
 

// A class that has a static data member

class Employee implements Serializable {

  int id;

  String name;

  static String company = "ABC"; // static data member

  public Employee(int id, String name) {

    this.id = id;

    this.name = name;

  }

}

// A class that serializes and deserializes an Employee object

public class StaticExample {

  public static void main(String[] args) {

    // Create an Employee object

    Employee e1 = new Employee(101, "Alice");

    // Change the value of the static data member

    Employee.company = "XYZ";

    // Serialize the object and write it to a file

    try {

      FileOutputStream fos = new FileOutputStream("employee.ser");

      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(e1);

      oos.close();

      fos.close();

      System.out.println("Object serialized");

    } catch (IOException e) {

      e.printStackTrace();

    }

    // Deserialize the object and read it from the file

    try {

      FileInputStream fis = new FileInputStream("employee.ser");

      ObjectInputStream ois = new ObjectInputStream(fis);

      Employee e2 = (Employee) ois.readObject(); // cast to Employee type

      ois.close();

      fis.close();

      System.out.println("Object deserialized");

      System.out.println("Id: " + e2.id);

      System.out.println("Name: " + e2.name);

      System.out.println("Company: " + e2.company); // static data member

    } catch (IOException | ClassNotFoundException e) {

      e.printStackTrace();

    }

  }

}

 

Output: 
 

Object serialized

Object deserialized

Id: 101

Name: Alice

Company: XYZ

 

Give your career as a Java Developer the ideal start with our JavaScript for Beginners Course. Sign up now!

Java Serialization Caveats

 There are several important considerations and caveats to keep in mind when working with Serialization in Java as explored below:

Inheritance and Composition 

When the java.io.Serializable interface is implemented by a class, all its sub-classes become serializable as well. Additionally, when an object has a reference to another object, these objects must implement the serializable interface separately, otherwise a NotSerializableException will be thrown:
 

public class Person implements Serializable {

    private int age;

    private String name;

    private Address country; // must be serializable too

}


Suppose one of the fields in a serializable object consists of an array of objects. In that case, all of these objects must be serializable, or else a NotSerializable Exception will be thrown.

Serial Version UID 

 The JVM associates a version (long) number with each serializable class. You can use it to verify that the saved and loaded objects have the exact attributes and are thus compatible with Serialization.

Most IDEs can generate this number automatically, and it is based on the class attributes, class name, and associated access modifiers. Any changes will result in a different number, and may cause an InvalidClassException.

If a serializable class does not declare a serialVersionUID, the JVM will automatically generate one at run-time. However, it’s highly recommended that each class declares its serialVersionUID, because the generated one is compiler dependent and may result in unexpected InvalidClassExceptions.

Custom Serialization in Java

Although Java provides a default method for object Serialization, Java classes can override this behaviour. Custom Serialization is especially beneficial when dealing with objects that contain unserializable attributes. This can be achieved by implementing two specific methods within the class intended for Serialization:
 

private void writeObject(ObjectOutputStream out) throws IOException;Copy


and
 

private void readObject(ObjectInputStream in) 

  throws IOException, ClassNotFoundException;Copy


With these methods, we can serialize the unserializable attributes into other forms that we can serialize:
 

public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    private transient Address address;

    private Person person;

    // setters and getters

    private void writeObject(ObjectOutputStream oos) 

      throws IOException {

        oos.defaultWriteObject();

        oos.writeObject(address.getHouseNumber());

    }

    private void readObject(ObjectInputStream ois) 

      throws ClassNotFoundException, IOException {

        ois.defaultReadObject();

        Integer houseNumber = (Integer) ois.readObject();

        Address a = new Address();

        a.setHouseNumber(houseNumber);

        this.setAddress(a);

    }

}

 

public class Address {

    private int houseNumber;

    // setters and getters

}

 

What is transient keyword? 

The transient keyword is a modifier that can be applied to instance variables in Java. It indicates that the variable should not be serialized when the object is converted to a stream of bytes for storage or transmission. Serialization is the process of saving the state of an object to a file or sending it over a network. Deserialization is the reverse process of restoring the object from the stream of bytes.

The transient keyword is useful for security and performance reasons. For example, if an object contains sensitive information such as a password, it can be marked as transient to prevent it from being exposed or leaked. Similarly, if an object contains a variable that can be derived or calculated from other variables, it can be marked as transient to reduce the size of the serialized data.

The syntax of using the transient keyword is:
 

transient ;

 

Conclusion 

Serialization in Java is an essential technique for preserving and transmitting object states. Understanding this concept enhances data handling and application efficiency, making it an indispensable tool for developers. We hope this blog helps you master this process and ensure seamless data storage, data transfer, and improved performance of your Java applications.

Want to get an understanding and develop your knowledge on the working of Java EE APIs, then signup for our Introduction To Java EE Training course now!   

Frequently Asked Questions

What is the difference between Serialization & Deserialization in Java? faq-arrow

Serialization in Java is the process of converting an object into a byte stream so that it may be quickly sent over a network, saved in a file, or stored in a database. Rebuilding an object from a byte stream is known as Deserialization.

What is the purpose of Serialization in Java? faq-arrow

Serialisation serves multiple purposes in Java including communication (Between two machines running the same code), deep copy (create an object’s exact replica without writing Clone() method) and caching.

What are the other resources provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide. 

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
 

What is the Knowledge Pass, and how does it work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds. 

What are related Courses and blogs provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers Java Training, including Java Programming, JavaScript for Beginners and Java Swing Development Training. These courses cater to different skill levels, providing comprehensive insights into How to Become a Java Developer.  

Our Programming and DevOps Blogs cover a range of topics related to Java, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
 

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

BIGGEST
NEW YEAR SALE!

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.