Java Serialization example

Serialized object. What does that mean? Java provides a functionality which represents an object as a sequence of bytes which include the object’s data and also information about the object’s type and the types of data stored in that object.

java-featured-image

When a serialized object has been written into a file, it can later be deserialized, which means the other way around – the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Serialization illustration java example

The byte stream created is platform independent. Which means that if an object is serialized on one platform, it can be deserialized on another.

ObjectInputStream and ObjectOutputStrem are high-level streams that contain the methods for serializing and deserializing an object.




ObjectInputStream provides a method called readObject() which retrieves an object and deserializes it. It returns an Object value which means that it will need to be casted to the appropriate data type. It throws IOException.

public final Object readObject()

ObjectOutputStream provides many write methods, but the most widely used is

public final void writeObject(Object object)

The writeObject() method serializes an object and sends it to the output stream. It may throw IOException if the serialization goes wrong.

So to visualize where exactly these methods fit in, let’s display them on the image above.

write_readObject java example

Example of Java Serialization

DemoObject.java

import java.io.*; 
  
public class DemoObject implements java.io.Serializable { 
    private String name; 
    private int age;
  
    public DemoObject (String name, int age) { 
        this.name = name; 
        this.age = age;  
    } 
    
    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

Main.java

import java.io.*;  
  
public class Main { 
    public static void main(String[] args) {    
        DemoObject objectExample = new DemoObject("John", 19); 
        String filename = "file.ser"; 
        DemoObject obj = null; 
          
        // serialization  
        try {    
            FileOutputStream file = new FileOutputStream(filename); 
            ObjectOutputStream output = new ObjectOutputStream(file); 
              
            output.writeObject(objectExample);    
            output.close(); 

            file.close(); 
              
            System.out.println("Serialization of object has been completed"); 
          } 
          
        catch(IOException err) { 
            System.out.println("IOException occurred"); 
        } 
        
        // Deserialization 
        try {    
            FileInputStream file = new FileInputStream(filename); 
            ObjectInputStream input = new ObjectInputStream(file); 
              
            obj = (DemoObject) input.readObject(); // cast to the appropriate type
              
            input.close(); 
            file.close(); 
              
            System.out.println("Deserialization of object has been completed"); 
            System.out.println();
            System.out.println("Values of deserialized object are:");
            System.out.println("==================================");
            System.out.println("Name = " + obj.getName()); 
            System.out.println("Age  = " + obj.getAge()); 
            System.out.println("==================================");
        } 
        catch(IOException err)  { 
            System.out.println("IOException is caught"); 
        } 
          
        catch(ClassNotFoundException err) { 
            System.out.println("ClassNotFoundException is caught"); 
        } 
  
    } 
}

Output:

Serialization of object has been completed
Deserialization of object has been completed

Values of deserialized object are:
==================================
Name = John
Age  = 19
==================================

Breakdown of the code implementation above

We have an DemoObject class, acting as a dummy class which we will serialize and then deserialize. It has 2 instance variables which we called name and age. We could make these variables public, however we want to always be safe so that’s why in the example above they have been declared as private.

Main.java casts writeObject and readObject and basically does the error handling and printing to the console. In the example, we have one object which is set to null. It is set to null because it acts as a “placeholder” for the deserialized object. Basically, we can copy the desirialized object into that null object.

null object purpose java example serialized deserialized

Note: if your editor shows this warning:

warning java

you may ignore it or configure your IDE to autogenerate an id. I always recommend to let your IDE create the unique identifier for you.

When is serialization required

Serialization is a generic and efficient protocol that transfers object between components. Serialization is used to transfer objects following this protocol.

One last note: always have in mind that objects serialized with one version of Java may not work on another version of Java. For example: it is not a good idea to serialize objects with Java 6, deserialize them with Java 8 and vice versa.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments