close
The Wayback Machine - https://web.archive.org/web/20240826181116/https://www.geeksforgeeks.org/serialization-in-java/
Open In App

Serialization and Deserialization in Java with Example

Last Updated : 27 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. serialize-deserialize-java 
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform. To make a Java object serializable we implement the java.io.Serializable interface. The ObjectOutputStream class contains writeObject() method for serializing an Object. 
 

public final void writeObject(Object obj)
throws IOException

The ObjectInputStream class contains readObject() method for deserializing an object. 
 

public final Object readObject()
throws IOException,
ClassNotFoundException

Advantages of Serialization 

  1. To save/persist state of an object. 
  2. To travel an object across a network.

 BERJAYA

Only the objects of those classes can be serialized which are implementing java.io.Serializable interface. Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote. 

Points to remember 

1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.
2. Only non-static data members are saved via Serialization process. 
3. Static data members and transient data members are not saved via Serialization process. So, if you don’t want to save value of a non-static data member then make it transient. 
4. Constructor of object is never called when an object is deserialized. 
5. Associated objects must be implementing Serializable interface. Example :

class A implements Serializable{

// B also implements Serializable
// interface.
B ob=new B();
}

SerialVersionUID The Serialization runtime associates a version number with each Serializable class called a SerialVersionUID, which is used during Deserialization to verify that sender and receiver of a serialized object have loaded classes for that object which are compatible with respect to serialization. If the receiver has loaded a class for the object that has different UID than that of corresponding sender’s class, the Deserialization will result in an InvalidClassException. 

A Serializable class can declare its own UID explicitly by declaring a field name. It must be static, final and of type long. i.e- ANY-ACCESS-MODIFIER static final long serialVersionUID=42L; If a serializable class doesn’t explicitly declare a serialVersionUID, then the serialization runtime will calculate a default one for that class based on various aspects of class, as described in Java Object Serialization Specification. However it is strongly recommended that all serializable classes explicitly declare serialVersionUID value, since its computation is highly sensitive to class details that may vary depending on compiler implementations, any change in class or using different id may affect the serialized data. It is also recommended to use private modifier for UID since it is not useful as inherited member. serialver The serialver is a tool that comes with JDK. It is used to get serialVersionUID number for Java classes. 

You can run the following command to get serialVersionUID serialver [-classpath classpath] [-show] [classname…] BERJAYA Example 1: 

Java




// Java code for serialization and deserialization
// of a Java object
import java.io.*;
 
class Demo implements java.io.Serializable
{
    public int a;
    public String b;
 
    // Default constructor
    public Demo(int a, String b)
    {
        this.a = a;
        this.b = b;
    }
 
}
 
class Test
{
    public static void main(String[] args)
    {  
        Demo object = new Demo(1, "geeksforgeeks");
        String filename = "file.ser";
         
        // Serialization
        try
        {  
            //Saving of object in a file
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);
             
            // Method for serialization of object
            out.writeObject(object);
             
            out.close();
            file.close();
             
            System.out.println("Object has been serialized");
 
        }
         
        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }
 
 
        Demo object1 = null;
 
        // Deserialization
        try
        {  
            // Reading the object from a file
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);
             
            // Method for deserialization of object
            object1 = (Demo)in.readObject();
             
            in.close();
            file.close();
             
            System.out.println("Object has been deserialized ");
            System.out.println("a = " + object1.a);
            System.out.println("b = " + object1.b);
        }
         
        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }
         
        catch(ClassNotFoundException ex)
        {
            System.out.println("ClassNotFoundException is caught");
        }
 
    }
}


Output :

Object has been serialized
Object has been deserialized
a = 1
b = geeksforgeeks

Example 2: 

Java




// Java code for serialization and deserialization
// of a Java object
import java.io.*;
 
class Emp implements Serializable {
private static final long serialversionUID =
                                 129348938L;
    transient int a;
    static int b;
    String name;
    int age;
 
    // Default constructor
public Emp(String name, int age, int a, int b)
    {
        this.name = name;
        this.age = age;
        this.a = a;
        this.b = b;
    }
 
}
 
public class SerialExample {
public static void printdata(Emp object1)
    {
 
        System.out.println("name = " + object1.name);
        System.out.println("age = " + object1.age);
        System.out.println("a = " + object1.a);
        System.out.println("b = " + object1.b);
    }
 
public static void main(String[] args)
    {
        Emp object = new Emp("ab", 20, 2, 1000);
        String filename = "shubham.txt";
 
        // Serialization
        try {
 
            // Saving of object in a file
            FileOutputStream file = new FileOutputStream
                                           (filename);
            ObjectOutputStream out = new ObjectOutputStream
                                           (file);
 
            // Method for serialization of object
            out.writeObject(object);
 
            out.close();
            file.close();
 
            System.out.println("Object has been serialized\n"
                              + "Data before Deserialization.");
            printdata(object);
 
            // value of static variable changed
            object.b = 2000;
        }
 
        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
 
        object = null;
 
        // Deserialization
        try {
 
            // Reading the object from a file
            FileInputStream file = new FileInputStream
                                         (filename);
            ObjectInputStream in = new ObjectInputStream
                                         (file);
 
            // Method for deserialization of object
            object = (Emp)in.readObject();
 
            in.close();
            file.close();
            System.out.println("Object has been deserialized\n"
                                + "Data after Deserialization.");
            printdata(object);
 
            // System.out.println("z = " + object1.z);
        }
 
        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
 
        catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundException" +
                                " is caught");
        }
    }
}


Output:

Object has been serialized
Data before Deserialization.
name = ab
age = 20
a = 2
b = 1000
Object has been deserialized
Data after Deserialization.
name = ab
age = 20
a = 0
b = 2000

Description for Output: You have seen while deserializing the object the values of a and b has changed. The reason being a was marked as transient and b was static. 

In case of transient variables:- A variable defined with transient keyword is not serialized during serialization process.This variable will be initialized with default value during deserialization. (e.g: for objects it is null, for int it is 0). 

In case of static Variables:- A variable defined with static keyword is not serialized during serialization process.This variable will be loaded with current value defined in the class during deserialization. 

Transient Vs Final:
final variables will be participated into serialization directly by their values.
Hence declaring a final variable as transient there is no use.
//the compiler assign the value to final variable

example:

final int x= 10;
int y = 20;
System.out.println(x);// compiler will replace this as System.out.println(10)->10
because x is final.
System.out.println(y);//20

Example 3: 

Java




//java code for final with transient
 
import java.io.*;
 
 
class Dog implements Serializable{
          int i=10;
          transient final int j=20;
}
class GFG {
    public static void main (String[] args)throws IOException,ClassNotFoundException
    {
          Dog d1=new Dog();
          //Serialization started
          System.out.println("serialization started");
          FileOutputStream fos= new FileOutputStream("abc.ser");
          ObjectOutputStream oos=new ObjectOutputStream(fos);
          oos.writeObject(d1);
          System.out.println("Serialization ended");
       
          //Deserialization started
          System.out.println("Deserialization started");
          FileInputStream fis=new FileInputStream("abc.ser");
          ObjectInputStream ois=new ObjectInputStream(fis);
          Dog d2=(Dog) ois.readObject();
          System.out.println("Deserialization ended");
          System.out.println("Dog object data");
          //final result
          System.out.println(d2.i+"\t" +d2.j);
    }
}


Output

serialization started
Serialization ended
Deserialization started
Deserialization ended
Dog object data
10    20

 



Previous Article
Next Article

Similar Reads

Customized Serialization and Deserialization In Java
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Why is custom serialization needed? During serialization, there may be data loss if we use the 'transie
4 min read
JDK Flight Recorder Event For Deserialization
JDK Flight Recorder (JFR) is a profiling and event collection framework provided by the Java Development Kit (JDK). It allows the recording and analysis of events and telemetry data generated by the JVM and applications running on it. One of the events that can be registered with JFR is the deserialization event. When a Java application deserialize
4 min read
Difference Between Serializable and Externalizable in Java Serialization
The process of writing the state of an object to a file is called serialization, but strictly speaking, it is the process of converting an object from java supported form into a file-supported form or network-supported form by using fileOutputStream and objectOutputStream classes we can implement serialization. But we can serialize only serializabl
6 min read
Serialization of Lambda Expression in Java
Here we will be discussing serialization in java and the problems related to the lambda function without the serialization alongside discussing some ways due to which we require serialization alongside proper implementation as in clean java programs with complete serialization and deserialization process using the function interface. Serialization
5 min read
Object Serialization with Inheritance in Java
Prerequisite: Serialization, Inheritance Serialization is a mechanism of converting the state of an object into a byte stream. The byte array can be the class, version, and internal state of the object. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persis
6 min read
Object Graph in Java Serialization
Most of you must be aware with the Serialization involving single object but have you ever thought what if the object has reference to other objects too. Will it be serialized? Will reference objects will be serialized? Answer to these queries is yes, you don’t have to explicitly serialize reference objects. Let's find out how this can be achieved.
2 min read
How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
Prerequisite: Singleton Pattern In this article, we will see what various concepts can break the singleton property of a class and how to avoid them. There are mainly 3 concepts that can break the singleton property of a class. Let's discuss them one by one. Reflection: Reflection can be caused to destroy singleton property of the singleton class,
6 min read
Java 8 | DoubleToIntFunction Interface in Java with Example
The DoubleToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToIntFunction type is used to define
1 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Math asin() method with Example
The java.lang.Math.asin() returns the arc sine of an angle in between -pi/2 and pi/2. Arc sine is also called as an inverse of a sine. If the argument is NaN or its absolute value is greater than 1, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument. Syntax : public static double asin(doubl
1 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
Java String isEmpty() method with example
Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of the String class is included in Java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0. Syntax of Java
3 min read
Java String contains() method with example
The java.lang.String.contains() method searches the sequence of characters in the given string. It returns true if the sequence of char values is found in this string otherwise returns false. Implementation of contains() methodpublic boolean contains(CharSequence sequence) { return indexOf(sequence.toString()) > -1; } Here conversion of CharSequ
2 min read
Java Math log() method with example
The java.lang.Math.log() method returns the natural logarithm (base e) of a double value as a parameter. There are various cases : If the argument is NaN or less than zero, then the result is NaN.If the argument is positive infinity, then the result is positive infinity.If the argument is positive zero or negative zero, then the result is negative
1 min read
Java String toCharArray() with example
The Java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string. Syntaxpublic char[] toCharArray();Return ValueIt returns a newly allocated character array.Example of Java String toCharArray()Example 1: Java Code // Java program to demonstrate // working of
1 min read
Java log10() with example
The java.lang.Math.log10() is one of the Java Math Library method which is used to return the base 10 logarithmic value of given double value as a parameter. There are various cases : If the argument is positive double value, Math.log10() method will return the logarithm of a given value. If the argument is NaN or less than zero, Math.log10() metho
2 min read
Java log1p() with example
The java.lang.Math.log1p() is one of the Java Math Library method which is used to return the natural logarithm of the sum of the arguments and 1.For the small values, the result of log1p(a) is much closer to the true result of ln(1 + a) than the floating-point evaluation of log(1.0 + a).There are various cases : If the argument is positive double
2 min read
Java Math hypot() method with Example
java.lang.Math.hypot() function is an inbuilt math function in Java that returns the Euclidean norm, [TEX] \sqrt{(x * x + y * y)} [/TEX]. The function returns sqrt(x2 + y2) without intermediate overflow or underflow. If either argument is infinite, then the result is positive infinity. If either argument is NaN and neither argument is infinite, the
1 min read
Java Math exp() method with Example
The java.lang.Math.exp() returns euler's number e raised to the power of a double value. If the argument is NaN, the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument is negative infinity, then the result is positive zero. Syntax : public static double exp(double a) Parameter : a : the expone
1 min read
Java Math getExponent() method with Example
The java.lang.Math.getExponent() returns the unbiased exponent used in the representation of a double or float. Note: If the argument is NaN or infinite of double or float type, then the result is (Double.MAX_EXPONENT + 1) or (Float.MAX_EXPONENT + 1). If the argument is zero or subnormal of double or float type, then the result is (Double.MIN_EXPON
2 min read
Java Math getExponent() method with Example
The java.lang.Math.getExponent() is a built-in math function which returns the unbiased exponent used in the representation of a float. If the argument is NaN or infinite, then the result is Float.MAX_EXPONENT + 1. If the argument is zero or subnormal, then the result is Float.MIN_EXPONENT -1. Syntax: public static int getExponent(float val) Parame
1 min read
Java Math expm1() method with Example
The java.lang.Math.expm1() returns ex -1. Note that for values of x near 0, the exact sum of expm1(x) + 1 is much closer to the true result of ex than exp(x). If the argument is NaN, the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument is negative infinity, then the result is -1.0. If the ar
2 min read
Java Math round() method with Example
The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long. If the argument is NaN, the result is 0. If the argument is negative infinity or any value less than or equal
2 min read
Math pow() method in Java with Example
The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter. There are some special cases as listed below: If the second parameter is positive or negative zero then the result will be 1.0.If the second par
2 min read
Java toRadians() method with Example
The java.lang.Math.toRadians() is used to convert an angle measured in degrees to an approximately equivalent angle measured in radians. Note: The conversion from degrees to radian is generally inexact. Syntax: public static double toRadians(double deg) Parameter: deg : This parameter is an angle in degrees which we want to convert in radians. Retu
1 min read
Java toDegrees() method with Example
The java.lang.Math.toDegrees() is used to convert an angle measured in radians to an approximately equivalent angle measured in degrees. Note: The conversion from radians to degrees is generally inexact; users should not expect cos(toRadians(90.0)) to exactly equal 0.0. Syntax: public static double toDegrees(double rad) Parameter: rad : This parame
1 min read
Java Math nextAfter() method with Example
The java.lang.Math.nextAfter() returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments are equal then the second argument is returned. Syntax of nextAfter() method// datatype can be float or double. public static dataType nextAfter(dataType st, dataType dir) Parameter : st : starti
2 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Article Tags :
Practice Tags :