Serialization in java

Serialization in Java

In this Tutorial, we will about serialization in Java i.e. what is serialization or serialization object in java and how it works. Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

The process in java where an object is converted in the form of bytes to store it in the memory, in a file or in any database is called serialization. We need to do serialization in order to recreate the object, whenever required by us. we sometimes need to change the state of an object because if JVM faces any issue, the object is automatically affected by it. Java objects are most probably not understand. whereas bytes are easy to understand. This process is done to retain the basic state of an object.

The byte stream that is created out of an object is platform-independent. Hence, it is not always compulsory to serialize and de-serialize the object on the same platform. The bytes can be again transformed into a live object later.  The revoking back of the process of serialization is called de-serialization.

The main advantages of serialising an object are:

  • To move an object across the data network.
  • To save the basic state of an object.
  • We can access the byte stream of the object in the database whenever we want, as it gets saved on the network.
  • It is very easy to understand and is customizable.
  • The serialized state can be revoked back.

How does serialization work in java?

Since you now know what serialization in Java is, and all the relevant points, let’s delve deep into how to serialize an object. You must use the writeObject() method of the ObjectOutputStream class for serialization and readObject() method of the InputObjectStream class for deserialization purpose.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. The ObjectOutputStream class contains many write methods for writing various data types

  • ObjectOutputStream.writeObject(): this will write a serializable object to the output stream. The method throws an exception as NotSerializableException.  Serializable interface cannot be implemented by the object to be serialized.
  • ObjectInputStream.readObject(): this will read, construct and return an object from the input stream. The method will throw an exception as ClassNotFoundException if class of a serialized object cannot be found.

Syntax for ObjectOutputStream.writeobject() :

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object –

Syntax of ObjectInputStream.readObject() : :

public final Object readObject() throws IOException, ClassNotFoundException

Let us Consider An Example about serialization in Java :

If you want a class object to be serializable, all you need to do it implement the java.io.Serializable interface. Serializable in java is a marker interface and has no fields or methods to implement. It’s like an Opt-In process through which we make our classes serializable. Serialization in java is implemented by ObjectInputStream and ObjectOutputStream, so all we need is a wrapper over them to either save it to file or send it over the network. Let’s see a simple Serialization in java program example https://www.developerhelps.com/contact/

package com.journaldev.serialization;

import java.io.Serializable;

public class Employee implements Serializable {

//	private static final long serialVersionUID = -6470090944414208496L;	
	private String name;
	private int id;
	transient private int salary;
//	private String password;
	
	@Override
	public String toString(){
		return "Employee{name="+name+",id="+id+",salary="+salary+"}";
	}	
	//getter and setter methods
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getSalary() {
	return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
//	public String getPassword() {
//		return password;
//	}
//
//	public void setPassword(String password) {
//		this.password = password;
//	}
	
}


Output :

emp Object::Employee{name=Pankaj,id=100,salary=5000}

empNew Object::Employee{name=Pankaj,id=100,salary=0}

Here is a Simple program to execute Serialization and de-serialization:

import java.io.*;

public class Demo implements java.io.Serializable {
    public int x;
    public String y;

    public Demo(int a, String b) {
        this.x = a;
        this.y = b;
    }

    public static void main(String[] args) {
        Demo object = new Demo(1, "developerhelps");
        String filename = "file.ser";

        try {
            // Performing Serialization
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);

            out.writeObject(object);

            out.close();
            file.close();

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

        } catch (IOException ex) {
            System.out.println("IOException is caught");
        }

        Demo objectnew = null;

        try {
            // Deserialization
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);

            objectnew = (Demo) in.readObject();

            in.close();
            file.close();

            System.out.println("Object has been deserialized ");
            System.out.println("x = " + objectnew.x);
            System.out.println("y = " + objectnew.y);
        } catch (IOException ex) {
            System.out.println("IOException is caught");
        } catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundException is caught");
        }

    }
}


Output :

Object has been deserialized
Object has been deserialized
a=1
b-= developerhelps

Important Points To Remember

To serialize an object, there are a few conditions to be met. Some other key points need to be highlighted before you proceed further in the article. These are the conditions and points to remember while using serialization in Java.

  • Serialization is a marker interface with no method or data member
  • You can serialize an object only by implementing the serializable interface
  • All the fields of a class must be serializable; otherwise, use the transient keyword (more about it later)
  • The child class doesn’t have to implement the Serializable interface, if the parent class does
  • The serialization process only saves non-static data members, but not static or transient data member
  • By default, the String and all wrapper classes implement the Serializable interface
  • If a parent class implements Serializable interface, then child class doesn’t require implementing it however it is not true for the opposite case.
  • We can only save non-static data members during the serialization process.
  • We cannot save static and transient data members via the serialization process. In case one doesn’t want to save a non-static data member, convert it to transient.
  • The constructor of object cannot be called if an object is not serialized.
  • The process of serialization is not dependent on any platform.
  •  The default process of serialization in java is recursive. It implies that if we try to serialize an object, Java will try to serialize the whole field.
  • none of the access specifiers such as ‘private’ work well for this process.

Leave a comment

Your email address will not be published. Required fields are marked *

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!