Friday, October 29, 2021

Java Serialization Example and Tutorial for Beginners [Guide]

Serializing an object in Java is never easy and many Java developers often get confused. There are so many rules, interfaces to implement, and then always a chance of data loss or an error during the Serialization or deserialization process.  In the past, I have posted a detailed guide of Serliazing Object in Java which is very liked by my readers and they asked for more information like what should Java developers remember while using the Serializable and Externalizable interface in Java. 

This encouraged me to write this post where I have put together 10 important points related to Serializing an Object in Java. This is a to-the-point article that is full of information and I have also shared a core example to demonstrate the point I have mentioned in this article.

If you are planning to use the Serliazation feature of Java then this quick guide can help you a lot but if you really want to master this tough concept then I strongly recommend you to read Seriliation related chapters from my favorite Java book, Effective Java. It contains the best advice on how to use Serialization in Java correctly.

This is also an advanced concept for many Java developers, this means if you don't know about Serliazation or Serializable, Externalizable interface then don't worry. Many people don't know, even after working for years.

However, if you want to improve your overall Java knowledge then I suggest you go through a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka and his team on Udemy. It's one of the most up-to-date courses to learn Java and also covers new Java features from recent releases. If you like free resources, you can also see my list of free courses to learn Java from scratch




10 Things about Serializable and Externalizable in Java

Anyway, without wasting any more of your time, here is a list of important things Java developers should remember while using the Serializable and Externalizable interface in their Java application.

1. Implement Serializable or Externalizable

Your class or superclass must implement a Serializable or Externalizable interface in order to be serialized or persisted, otherwise, it will throw java.lang.NotSerializableException during serialization in Java:

Exception in thread "main" java.io.NotSerializableException: test.Order
        at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)


2. Use ObjectOutputStream and ObjectInputStream for Persist

The ObjectOutputStream class is used to serialize objects and can be saved into a file or transferred across the network. On the other hand, ObjectInputStream is used to read or restore the object from the serialized form.


3. writeObject() and readObject()

The ObjectOutPutStream.writeObject() kicks off seralizeation process and ObjectInputStream.readObject()  kicks off the deserilization or restoration process.


4. Customization of writeObject()

If the Serializable class implements the readObject() or writeObject() method then those are invoked during the Serialization process.


5. No Argument Constructor

During the restoration process, if your Class implements Externalizable interface Objects are created by calling a no-argument constructor, So a Serializable class must provide a no-argument constructor.

6. What can you do inside writeObject

If your class implements private void writeObject(ObjectOutputStream out) throws IOException and private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException then JVM will call this method and give you an opportunity to customize the serialization process. you can perform additional tasks here like starting the timer, encryption or compression, etc.


7. transient and static fields are not serialized

Both transient and static fields are not stored during Serialization in Java and when an object gets created it's your responsibility to provide the correct values.


8. Preventing Serialization of a class

In order to prevent a class from being serialized, first, don't implement Serializable or Externalizable but if your superclass is implementing Serializable and you just want subclass not to be serialized then declare readObject() and writeObject() method in your class and throw java.lang.NotSerializableException from them, as shown in the below Example:

 private void writeObject(ObjectOutputStream out) throws IOException{ 
        throw new NotSerializableException("Sorry I am not Serializable");
 
} 
 
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{ 
        throw new NotSerializableException("Sorry I am not Serializable");
 
}

9. What is saved during Serialization

Only the object's state is saved during Serialization and no Class or method is saved.


10. Constructor Chaining

During the restoration of Object, JVM calls the constructor of superclass until it reaches a class that is not serialized.

These are the important points every Java developer should remember while serializing objects in Java or using Serializable or Externalizable interfaces. As I have said, a good knowledge of this topic is very important for Java programmers and if you want to learn more, I strongly suggest you join a good Java course like Java In-Depth: Become a Complete Java Engineer! Udemy.

10 things to Remember while Serializing Object in Java



How to use Serializable Interface in Java

Now that you know how to use the Serializable and Externalizable interface in Java, it's time to see a complete code example. In this Java program, I have a class called Order which implements a Serializable interface. You will learn how to save and restore the state of the Order object using the Serialization process in Java.

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.NotSerializableException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.io.Serializable; 
import java.math.BigDecimal;
 
public class JavaSerializationDemo {
 
  public static void main(String args[]) throws FileNotFoundException,
      IOException, ClassNotFoundException {
 
    Order firstOrder = new Order(1, "Sony", BigDecimal.valueOf(1000));
 
    // serializing firstOrder 
    FileOutputStream fos = new FileOutputStream("order.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fos); 
    out.writeObject(firstOrder); 
    out.close();
 
    // Now you should have file called order.ser which contains firstOrder state
    // in serialized format.
 
    // reading serialized object in Java
 
    FileInputStream fis = new FileInputStream("order.ser"); 
    ObjectInputStream in = new ObjectInputStream(fis); 
    Order firstOrderFromSerialization = (Order) in.readObject(); 
    System.out.println(firstOrderFromSerialization);
 
    // output
 
    // id: 1 customer: Sony amount: 1000
 
  }
 
}
 
class Order implements Serializable {
 
  private int id; 
  private String customer; 
  private BigDecimal amount;
 
  public Order(int id, String customer, BigDecimal amouant) { 
    this.id = id; 
    this.customer = customer; 
    this.amount = amouant; 
  }
 
  public BigDecimal getAmouant() { 
    return amount; 
  }
 
  public void setAmouant(BigDecimal amouant) { 
    this.amount = amouant; 
  }
 
  public String getCustomer() { 
    return customer; 
  }
 
  public void setCustomer(String customer) { 
    this.customer = customer; 
  }
 
  public int getId() { 
    return id; 
  }
 
  public void setId(int id) { 
    this.id = id; 
  }
 
  @Override
  public String toString() { 
    return "id: " + id + " customer: " + customer + " amount: " + amount; 
  }
 
//  private void writeObject(ObjectOutputStream out) throws IOException {
//
//    throw new NotSerializableException("Sorry I am not Serializable");
//
//  }
//
//  private void readObject(ObjectInputStream in) throws IOException,
//      ClassNotFoundException {
//
//    throw new NotSerializableException("Sorry I am not Serializable");
//
//  }
 
}

Output and Explanation

When you run this program the first time it will create an Order instance that implements a Serializable interface. After that, you save that order instance into a file called "order.ser" by using ObjectOutputStream and FileOutputStream.  You can see the file in your Eclipse project after you run this program as shown below:

How to use Serializable Interface in Java

After saving the object, we start the process of restoring the instance of Order and read the data from this file to create the Order object back. In the code, you can see that we are casting the value returned by readObject() into Order and then printing it again.

If you compare this object has the same value as the original object which means both Serialization and Deserialization was successful. Now, if you run the program again by un-commenting the code for writeObject() and readObject() then you will see that the code throws the NotSerlizableException and the file is not created, provided you have already deleted the file.

This proves that if you have the writeObject() or readObject() method in your class then they are called by JVM during the serialization and de-serialization process and you can abort the Serialization process by throwing the NotSerlizableException in Java.


That's all about the important things about the Serialization process in Java. I have shared a lot of useful information in Java bout the Serializable and Externalizable interfaces in Java, how they work, how to serializable an object,t how to restore it, and even how to prevent the serialization of an object in Java. It's a complex process and you may take some time to digest the information given here but that's fine, you can bookmark the article and keep reading it whenever you want.


Other Java serialization tutorials you may like to explore
  • 5 Best Java Programming Courses for Beginners (courses)
  • Difference between Serializable and Externalizable in Java? (answer)
  • 10 Free Java Programming Courses for Developers (free courses)
  • 10 Advanced Core Java Books for Java Programmers (books)
  • Why should you use SerialVersionUID in Java? (answer)
  • 5 Best Courses to learn Spring MVC in depth (courses)
  • Google Protocol Buffer - a fast alternative of serialization in Java? (tutorial)
  • My favorite Courses to learn Spring Boot in-depth (courses)
  • Difference between the transient and volatile variables in Java? (answer)
  • 5 Free Courses to learn Spring Core and Spring MVC (free courses)
  • How to use a transient variable in the Serializable class? (answer)
  • 5 Best Hibernate Courses for Java developers (best courses)
  • What Every Java developer should know about Serialization (read)
  • Top 10 Serialization Interview Questions for Programmers (questions)
  • 10 Advanced Core Java Courses for Java developers (courses)

Thanks for reading this article so far, If you like this Java Serialization Tutorial for beginners then please share it with your friends and colleague. If you have any questions or feedback then please drop a note.

P. S. - If you are new to the Java world and want to learn Java from scratch but looking for some free courses to start with then you can also check out Java Tutorial for Complete Beginners(FREE) a hands-on, and a free course on Udemy. All you need to do is create a free Udemy account and enroll in this course.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.