Home  >  Core Java

Example of Serialization and Deserialization in Java

By Arvind Rai, December 09, 2012
A java class can be saved in byte stream with a version id and can be invoked again. Saving class in byte stream is called Serialization and fetching that class is called Deserialization.. To achieve this, a class has to implement java.io.Serializable interface. This interface has no method. This is a marker interface. If super class has implemented Serializable interface, then subclass will also be serialized. While saving class in byte stream java uses a default serialVersionUID.. Java VM deserializes the class on the basis of serialVersionUID to get the correct version of serialized class. Java recommends to define serialVersionUID. It is defined as
public static final long serialVersionUID = 42L;
Access modifier can also be protected or private.. Find the example.
ConcretePage.java
package com.concretepage;

import java.io.Serializable;

public class ConcretePage implements Serializable {
	public static final long serialVersionUID = 1L;
	private String user;
	public ConcretePage(String user){
		this.user=user;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
}
ConcreteMain.java
 package com.concretepage;

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

public class ConcreteMain {
   public static void main(String... args) throws Exception, IOException{
	   File f= new File("a.txt");
	   ConcretePage cp= new ConcretePage("Ankita");
	   ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));  
       out.writeObject(cp);  
      
       ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
       cp=(ConcretePage)in.readObject();
       System.out.println("After deserialize user is: " +cp.getUser());   
   }
}
ConcretePage.java is class that implements serializable . In the class ConcreteMain.java a file has been defined to write byte stream. Then object has been created and the serialized and then deserialized.

Use of Serialization

1. Convert java object into byte stream and then it can be saved in database for persistence. 2. If two JVM want to communicate, then object serialization is one of the approaches. 3. Send the java object in network as byte stream by serialization and at the other end deserialize to get same object in same state. 4. Cache the object by serialization instead of keeping it in memory.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us