beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java Serialization

By Chaitanya Singh | Filed Under: Java Tutorials

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

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 Index
  • Java Introduction
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Control Statements

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

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • 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 Interview Q

MORE ...

  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap