Serialization in Java is the process of converting an object into a byte stream so it can be saved to a file, sent over a network, or stored in memory. Deserialization is the reverse process of reconstructing the object from the byte stream.
Serializable interfaceA class must implement the Serializable interface to allow its objects to be serialized. This interface is marker-based and does not contain any methods.
// Serializable class definition
import java.io.Serializable;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
// Serialization process
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) throws Exception {
Student s1 = new Student(101, "Amit");
FileOutputStream fout = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(s1);
out.close();
fout.close();
}
}
The object Student is converted into a byte stream and stored in a file named student.ser. This file can later be used to restore the object.
Fill the object fields below and click Serialize to see how Java converts data into bytes. Use the transient checkbox to see how data is ignored.
transient keyword to skip fields from serializationserialVersionUID for version controltransient and observe behavior