BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Serialization

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Here we are gonna discuss how to serialize and de-serialize an object and what is the use of it.

What is Java Serialization?

Serialization is a mechanism to convert an object into stream of bytes so that it can be written into a file, transported through a network or stored into database. De-serialization is just a vice versa. In simple words serialization is converting an object to stream of bytes and de-serialization is rebuilding the object from stream of bytes. Java Serialiation API provides the features to perform seralization & de-serialization. A class must implement java.io.Serializable interface to be eligible for serialization.

Lets take an example to understand the concepts better:

Example
This class implements Serializable interface which means it can be serialized. All the fields of this class can be written to a file after being converted to stream of bytes, except those fields that are declared transient. In the below example we have two transient fields, these fields will not take part in serialization.
Student.java

public class Student implements java.io.Serializable{
  private int stuRollNum;
  private int stuAge;
  private String stuName;
  private transient String stuAddress;
  private transient int stuHeight;
 
  public Student(int roll, int age, String name,
  String address, int height) {
    this.stuRollNum = roll;
    this.stuAge = age;
    this.stuName = name;
    this.stuAddress = address;
    this.stuHeight = height;
  }
 
  public int getStuRollNum() {
    return stuRollNum;
  }
  public void setStuRollNum(int stuRollNum) {
    this.stuRollNum = stuRollNum;
  }
  public int getStuAge() {
    return stuAge;
  }
  public void setStuAge(int stuAge) {
    this.stuAge = stuAge;
  }
  public String getStuName() {
    return stuName;
  }
  public void setStuName(String stuName) {
    this.stuName = stuName;
  }
  public String getStuAddress() {
    return stuAddress;
  }
  public void setStuAddress(String stuAddress) {
    this.stuAddress = stuAddress;
  }
  public int getStuHeight() {
    return stuHeight;
  }
  public void setStuHeight(int stuHeight) {
    this.stuHeight = stuHeight;
  }
}

Serialization of Object

This class is writing an object of Student class to the Student.ser file. We are using FileOutputStream and ObjectOutputStream to write the object to File.

Note: As per the best practices of Java Serialization, the file name should have .ser extension.

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SendClass
{
  public static void main(String args[])
  {
    Student obj = new Student(101, 25, "Chaitanya", "Agra", 6);
    try{ 
      FileOutputStream fos = new FileOutputStream("Student.ser"); 
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
      oos.close();
      fos.close();
      System.out.println("Serialzation Done!!");
   }catch(IOException ioe){
      System.out.println(ioe);
    }
  }
}

Output:

Serialzation Done!!

De-serialization of Object

This class would rebuilt the object of Student class after reading the stream of bytes from the file. Observe the output of this class, student address and student height fields are having null & 0 values consecutively. This is because these fields were declared transient in the Student class.

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class AcceptClass {

 public static void main(String args[])
 {
    Student o=null;
    try{
      FileInputStream fis = new FileInputStream("Student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      o = (Student)ois.readObject();
      ois.close();
      fis.close();
    }
    catch(IOException ioe)
    {
       ioe.printStackTrace();
       return;
    }catch(ClassNotFoundException cnfe)
     {
       System.out.println("Student Class is not found.");
       cnfe.printStackTrace();
       return;
     }
    System.out.println("Student Name:"+o.getStuName());
    System.out.println("Student Age:"+o.getStuAge());
    System.out.println("Student Roll No:"+o.getStuRollNum());
    System.out.println("Student Address:"+o.getStuAddress());
    System.out.println("Student Height:"+o.getStuHeight());
 }
}

Output:

Student Name:Chaitanya
Student Age:25
Student Roll No:101
Student Address:null
Student Height:0

Top Related Articles:

  1. Java 8 features with examples
  2. Method Overloading in Java with examples
  3. Multilevel inheritance in java with example
  4. Constructor Overloading in Java with examples
  5. Java 8 Stream – noneMatch() example

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Shrikant says

    October 8, 2015 at 11:17 AM

    Hi,
    I have been a regular user of this website for my core Java interview preparation.
    It has a very good content but not organized properly.
    E.g I won’t be able to find sterilization directly from main page so I need to find it from Google.

    So if you could provide a full index page and link all these topics to it then it would
    Be really helpful for someone who is preparing for interviews. As in this way he can keep a track of covered topics.

    Please consider my suggestion as it will lot of people like me.

    Reply
    • Aditya R says

      June 19, 2017 at 6:39 AM

      Yes, even I felt the same but anyways its properly explained .
      Thanks for taking time and explaining all the important concepts neatly and clearly.

      Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap