• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Serialization and Deserialization in Java with Example

February 23, 2015 by javainterviewpoint Leave a Comment

Java Serialization allows us to convert Java Object to a Stream of bytes which we can send through a network or save in a flat file or even in a DB for future usage.Deserialization is the process of converting a stream of bytes back to Java Object which can be used in our program. We will be implementing java.io.Serializable interface to achieve serialization

Serializable Interface

The serializable interface in java is a marker interface(method with no body). It adds serialization capabilities to the class Employee. Even though it is a marker interface it must be implemented in the class whose object you want to persist.

import java.io.Serializable;

public class Employee implements Serializable
{
	private int empId;
    private String empName;
	
    public int getEmpId() {
        return empId;
    }

    public String getEmpName() {
        return empName;
    }

    public Employee(int empId,String empName)
    {
        this.empId=empId;
        this.empName=empName;
    }
}

Java Serialization Example

We will be using java.util.ObjectOutputStream and java.util.ObjectInputStream to write/read object to/from the file “Persist.txt”

SerializationUtility.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationUtility
{
    //Method to serialize and save the object in the file
    public void serialize(Object obj,String filePath)
    {
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(obj);
            outputStream.flush();
            outputStream.close();
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
    }
    
    //Method to deserialize and return the object
    public Object deSerialize(String filePath)
    {
        Object obj = null;
        try
        {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
            obj = inputStream.readObject();
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
        return obj;
    }
}

Our SerializationUtility class has two methods

  • serialize() : we will make use of java.util.ObjectOutput stream to write the Object which we pass, to the file “Persist.txt”
  • deSerialize(): java.util.ObjectInputStream is used to read the Object from the file and return it back to the user.

Client.java

public class Client 
{
    public static void main(String args[])
    {
        //Path to store the Serialized object
        String filePath="D://Persist.txt";
        Employee emp = new Employee(1,"JavaInterviewPoint");
        
        SerializationUtility su = new SerializationUtility();
        
        //Serialize emp object
        su.serialize(emp, filePath);
        
        //De-Serialize Employee object
        Employee ee = (Employee)su.deSerialize(filePath);
        System.out.println("Employee id : "+ee.getEmpId());
        System.out.println("Employee Name : "+ee.getEmpName());
    }
}

In our Client.java we have called the serialize() and deSerialize() methods. When we run the above program we will get the output as below and you will have physical file created at your D: Drive

Employee id : 1
Employee Name : JavaInterviewPoint

Is sub class Serializable?

If the parent class is Serializable then all the sub class which extends our parent class will be Serializable as well.

Employee.java

public class Employee implements Serializable
{
    private static final long serialVersionUID = 5414347551602268992L;
	private int empId;
    private String empName;
    
	public int getEmpId() {
        return empId;
    }

    public String getEmpName() {
        return empName;
    }

    public Employee(int empId,String empName)
    {
        this.empId=empId;
        this.empName=empName;
    }
}

Person.java

public class Person extends Employee{

    private String personName;
    
    public Person(String personName)
    {
        super(2,"Java");
        this.personName=personName;
        
    }
    public String getPersonName() {
        return personName;
    }
}

Here parent class which our Employee.java is Serializable and hence the sub class (Person.java) which extends our parent class is also Serializable.

Other Class Reference in a Serializable class

If we have a non-serializable reference of a class inside a Serializable class, then serialization operation will not be performed.In such case, NonSerializableException will be thrown. Let’s look into the below code.

Employee.java
Employee class is Serializable

public class Employee implements Serializable
{
    private static final long serialVersionUID = 5414347551602268992L;
	private int empId;
    private String empName;
    
    Location l;
    
	public static long getSerialversionuid() {
        return serialVersionUID;
    }

    public Location getL() {
        return l;
    }

    public int getEmpId() {
        return empId;
    }

    public String getEmpName() {
        return empName;
    }

    public Employee(int empId,String empName,Location l)
    {
        this.empId=empId;
        this.empName=empName;
        this.l = l;
        l.setAddress("Chennai");
    }
}

Location.java
Location class is non Serializable

public class Location
{
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Client.java

public class Client 
{
    public static void main(String args[])
    {
        //Path to store the Serialized object
        String filePath="c://Persist.txt";
        Employee emp = new Employee(1,"JavaInterviewPoint",new Location());
        
        SerializationUtility su = new SerializationUtility();
        
        //Serialize emp object
        su.serialize(emp, filePath);
        
        //De-Serialize Employee object
        Employee ee = (Employee)su.deSerialize(filePath);
        System.out.println("Employee id : "+ee.getEmpId());
        System.out.println("Employee Name : "+ee.getEmpName());
        System.out.println("Location : "+ee.getL().getAddress());
    }
}

Now when we run our Client.java we will get java.io.NotSerilizableException

Caused by: java.io.NotSerializableException: com.javainterviewpoint.Location
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
	at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.writeObject(Unknown Source)
	at com.javainterviewpoint.SerializationUtility.serialize(SerializationUtility.java:17)
	at com.javainterviewpoint.Client.main(Client.java:14)

As the Location class is not Serializable.

Other interesting articles which you may like …

  • What is the use of Java Transient Keyword – Serialization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Constructor in Java and Types of Constructors in Java
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method
  • Java Constructor.newInstance() method Example
  • Parameterized Constructor in Java with Example
  • Sort Objects in a ArrayList using Java Comparator
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Difference between equals() and ==
  • Difference Between Interface and Abstract Class in Java
  • Difference between fail-fast and fail-safe Iterator
  • Difference between Enumeration and Iterator??
  • Difference between HashMap and Hashtable | HashMap Vs Hashtable

Filed Under: Core Java, Java Tagged With: Java, Serialization, Serialization Example

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·