Serialization and deserialization are crucial to stream handling in Java.
When you serialize an object in Java, you convert it to a byte stream in order to store or transmit the object to memory, a database, or a file. The byte stream is platform-independent, which means after serializing the object on one platform, it can be converted back to the original state on any other platform.
Deserializing simply undoes that process. In deserialization, an object is reconstructed back from the sequence of bytes.
How to achieve serialization in Java?
Serialization in Java is achieved by using a marker interface called Serializable, which is a part of the java.io package. A marker interface is an interface with no fields or methods. It just adds some special behavior to a class.
Let’s understand with the below example, how a student class implements a serializable interface.
import java.io.Serializable;
public class Student implements Serializable{
String name;
int age;
public Student( String name, int age ) {
this.name = name;
this.age = age;
}
// Getter and Setter Methods
public void displayName(){
System.out.println(“The Student Name is: ” +this.name);
}
}
public class Serialize{
public static void main(String[] args){
try {
//creating Student object
Student student = new Student(“John”, 31);
//writing data to file
FileOutputStream fos = new FileOutputStream(“file.txt”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
//serializing an object
oos.writeObject(student); //Methods of ObjectOutputStream Class
oos.close();
fos.close();
System.out.println(“Object is serialized successfully…”);
}catch(IOException e) {
System.out.println(e);
}
}
}
Above, we have imported the Serializable interface, which is implemented by the Student class. Thus, all the objects of the Student class can be converted into a byte stream.
After implementing Serializable interface, serializable behavior is added to the class. For writing data to file, we have the FileOutputStream Class and for writing objects into a stream, we have the ObjectOutputStream Class in Java. The objects can be passed as arguments to the writeObject() methods of ObjectOutputStream Class. The state of the object is saved to the file “file.text”.
Quick Tip: When a class implements serializable, all the objects of the class are serializable, and if you want any field not to be serialized, then it should be marked transient.
Eg:
transient private int age;
Deserialization:
public class Serialize{
public static void main(String[] args){
try {
//reading data from file
FileInputStream fis = new FileInputStream(“file.txt”);
ObjectInputStream ois = new ObjectInputStream(fis);
//deserializing an object
Student student = (Student)ois.readObject(student); //Methods of ObjectInputStream Class
student.displayName();
ois.close();
fis.close();
System.out.println(“Object is deserialized successfully…”);
}catch(ClassNotFoundException e) {
System.out.println(e);
}
}catch(IOException e) {
System.out.println(e);
}
}
}