Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Object Serialization and Deserialization in Java

In this article we will talk about Object Serialization and Deserialization using the language Java.

Introduction

Object Serialization and Deserialization is a very interesting topic in Java. It is the most common topic in Java about which most of the people are either unaware or having so much of misconception in their mind. It is the most common topic which is frequently asked in many technical interviews. Before going into Java classes and codes I would like to elaborate this topic in very simple way. In our daily life we all use refrigerators to make Ice and stoves to melt that ice. In the process of making Ice and Melting Ice one thing is very common. It is that, always water becomes Ice when freezed and Ice becomes Water. It never happens that water would have become a Rock or Ice would have melted into Olive Oil. After melting water has the same state as it has when this was freezed. This mechanism is called persistence.

Object Serialization and Deserialization

Figure 1: Object Serialization and Deserialization

So the same process is followed in Java while serialization and Deserialization. In Java, through Object Serialization, an Object can be transformed into a sequence of bytes and in the reverse process, Deserialization, Original Object is reproduced. Now always one question will be in your mind, what do you mean by an Object? Answer is: anything which extends java.lang.Object is an Object. It might be a wrapper class or String or any other class. In the process of Serialization below three are stored in form of bytes:

  1. Object’s Data
  2. Type of Object.
  3. Type of Data stored in Object.

Most interesting fact about serialization and Deserialization is, this whole process is platform and JVM independent. Suppose an Object is serialized in windows platform, can be desterilized into Linux. Now you will start thinking how is it possible? I will say wait and read. You will find the answer of this question in the end of this article.

Now I hope after reading the above, you might be having some overview about Object Serialization and Deserialization process.

Implementing Serialization and Deserialization in Java

In Java Object Serialization is implemented with the help of ObjectInput and ObjectOutput interfaces, which extends DataInput and DataOutput interfaces, respectively. ObjectOutputStream class and the ObjectInputStream class implement the ObjectOutput interface and the ObjectInput interface, respectively. These two classes provides some set of methods which helps in writing and reading binary form of Object and Primitive values (int,long,double etc.). Below are the set of methods which are provided by below classes:

1. ObjectOutputStream :

  • writeInt(i)
  • writeLong(l)
  • writeShort(s)
  • writeChars(str)
  • writeUTF(str)
  • writeBoolean(b)
  • writeByte(i)
  • writeChar(i)
  • writeDouble(d)
  • writeFloat(f)
  • writeObject(o)

ObjectOutputStream class can write object to any stream which extends Outputstream class. ObjectOutputStream class is used in serialization process.

2. ObjectInputStream :

  • readInt()
  • readLong()
  • readShort()
  • readLine()
  • readUTF()
  • readBoolean()
  • readByte()
  • readChar()
  • readDouble()
  • readFloat()
  • readObject()

ObjectInputStream class can read bytes and converts them in to object so it plays role in Deserialization process.

Above read and write methods are the method of Abstract Classes OutputStream and InputStream classes. These methods can throw IOException and EOFException. EOFEception is thrown if the end of stream is reached.

Serialization and Deserialization in a File

We can better understand this whole process with the help of below example:

I am going to explain Serialization and Deserialization with the help of a file. Suppose we have a file test.txt. We will store an Object in this file in form of bytes and then we recreate that object from the same file.

Serialization and Deserialization with the help of a file

Figure 2: Serialization and Deserialization with the help of a file

Listing 1: Serialization and Deserialization in a File

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.io.EOFException;
import java.io.FileNotFoundException;

public class Serializationtest {
	void writeO(){
	//Writing Object in form of Bytes (serialization)
		 try {
			FileOutputStream  testFile = new FileOutputStream("test.txt");
			//passing FileOuputStream object into ObjectOutputStream
			ObjectOutputStream outputOStream = new ObjectOutputStream(testFile);
			String [] str1 = {“Hi” , “Hello” , “Hey” , “Hola” , “wazup” };
			int [] nums = { 5,15,25,25,36};
			outputOStream.writeObject(str1);
			outputOStream.writeObject(nums);
			outputOStream.flush();
			outputOStream.close();

		}catch (FileNotFoundException e) {

			System.err.println("File not found: " + e);

		} catch (IOException e) {

			System.err.println("Write error: " + e);

		}
	}

	void readB(){
	//Reading Bytes and converting and recreating Object.
		try {

		FileInputStream itestFile = new FileInputStream("test.txt");
		//passing FileInputStream Object into ObjectInputStream
		ObjectInputStream inputOStream = new ObjectInputStream(itestFile);
		String[] str1 = (String[]) inputOStream.readObject();
		int[] nums = (int[]) inputOStream.readObject();
		System.out.println(Arrays.toString(str1));
		System.out.println(Arrays.toString(nums));
		inputOStream.close();

		}catch (FileNotFoundException e) {

			System.err.println("File not found: " + e);

		}catch (EOFException e) {

			System.err.println("End of stream: " + e);

		}catch (IOException e) {

			System.err.println("Read error: " + e);

		}catch (ClassNotFoundException e) {

			System.err.println("Class not found: " + e);
		}
	}
	
	public static void main(String...args){

		Serializationtest  t1 = new  Serializationtest();

		t1.writeO();
		t1.readB();
	}
} 

Output of after running class file:

[Hi , Hello , Hey , Hola , wazup]
[5,15,25,25,36]

*Please save .java file same as class name because we have taken a public class.

In the above program we have serialized String Array and int Array into Bytes and wrote on a file and then we again deserialized and recreated the same object.

Now I want you to do some changes in the code and discover some new thing in serialization and Deserialization. In the above code we are firstly writing String array and following the same while reading from file. I want you to reverse the process of reading.

int[] nums = (int[]) inputOStream.readObject();
String[] str1 = (String[]) inputOStream.readObject();

Comiple the .java file again and rerun the same. You will be seeing below Exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to [I
        at Serializationtest.readB(Serializationtest.java:43)
        at Serializationtest.main(Serializationtest.java:66)

In the process of Deserialization we must follow the same sequence, in which Object was serialized. I want you to do one more thing. Please open test.txt.

Ljava.lang.String

Figure 3: Ljava.lang.String

You are seeing Ljava.lang.String. It shows type of object. Now I suppose that you have got the answer of your question. After Serialization information about object’s type is also stored. That is why this mechanism is JVM independent. You can discover other things too. Create your own program and make changes and see results and conclude more and more about this.

Use of Object Serialization and Deserialization

Now I hope that your concept about Object Serialization and Deserialization are pretty clear. Now the most important question is where we can apply this. Because if we cannot apply this, reading this core concept is worthless. Before I start explaining you about use, I would like to tell you one more interesting thing. Only those Objects can be serialized which implements java.io.Serializable interface. If a nonserializable object will be tried to serialized it will throw java.io.NotSerializableException.

Now I will explain you about use of Object serialization and Deserialization. As I have already explained that this process ensures persistence. To ensure that Object get created with same information and state.

Suppose you have a situation where you need to store an object of class in to a file or you need to store a state of an Object into a file. I have explained this with the help of below example:

Example: Suppose we have a student class. A student can have following properties:

  1. Roll No.
  2. Standard
  3. Section
  4. Name

And an object of class Student can have multiple state(for different Roll No). We can store different state of object into a file and we can recreate the object.

Listing 2: Recreating the object

import java.io.*;

public class Student implements java.io.Serializable
{

public String Roll_No ;
public String Standard ;
public String Section;
public String name;

}

import java.io.*;

public class StudentSerialize{

 public static void main(String...args)  {
    Student s1 = new Student();
    s1.Roll_No = "A101";
    s1.Standard = "X";
    s1.Section = "C";
    s1.name = "Dave";
    
     try { 
            FileOutputStream Studrec = new FileOutputStream("Student_Rec.txt");
            ObjectOutputStream Os = new ObjectOutputStream(Studrec);
            Os.writeObject(s1); 
            Os.flush();
            Os.close();
      
      }catch (FileNotFoundException e){
           System.err.println("File not found: " + e);
      
      }catch (IOException e){
           System.err.println("Write error: " + e);
      }
   }
 }    


import java.io.*;
public class StudentDeserialize{
  public static void main (String...args){

    Student s = null;
     try {
        FileInputStream Stud_Rec1 = new FileInputStream("Student_Rec.txt");
        ObjectInputStream Is = new ObjectInputStream (Stud_Rec1);
        
        s = (Student) Is.readObject();
        Is.close();
      
      }catch (FileNotFoundException e) {
        System.err.println("File not found: " + e);
      
      }catch (EOFException e){
        System.err.println("End of stream: " + e);
      }catch (IOException e){
         System.err.println("Read error: " + e);
      }catch (ClassNotFoundException e){
         System.err.println("Class not found: " + e);
      }

        System.out.println("Roll No -"+s.Roll_No);
        System.out.println("Standard -"+s.Standard);
        System.out.println("Section -"+s.Section);
        System.out.println("Name -"+s.name);
       
  }
}   

Output:

Roll No -A101
Standard -X
Section -C
Name -Dave

*Save all the above three program in the same directory.

So I hope now you are clear with usage of object Serialization and Deserialization.

Apart from above Object Serialization and Deserialization is widely used in Remote Method Invocation.

Note: If we want any non-serializable component to be involved into Serialization process then declare them with transient. Like Primitive values (int, char,byte etc.).

public  int transient seat_no;

Conclusion

This is all for today’s article, hope you liked. See you next time.



Assistant System Engineer na Tata Consultancy Services. Bachelor of Technology (B.Tech.), Computer Science na Uttar Pradesh Technical University.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login