Serialization in Java is a mechanism of converting an object into a stream of bytes which can be saved to a file or transferred over a network. The reverse process of creating an object from the stream of bytes is known as deserialization.
To make a class serializable, it must implement the java.io.Serializable interface. This interface does not have any methods and is used only to mark the class as serializable. If a class implements the Serializable interface, then all its non-transient instance variables will be serialized. The transient keyword is used to mark variables that should not be serialized.
Here is an example of how to serialize and deserialize an object in Java:
import java.io.*;
public class Student implements Serializable {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public static void main(String[] args) throws Exception {
// create a Student object
Student student = new Student(101, "John");
// serialize the object to a file
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(student);
oos.close();
// deserialize the object from the file
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student student2 = (Student) ois.readObject();
ois.close();
// print the values of the deserialized object
System.out.println("Id: " + student2.getId());
System.out.println("Name: " + student2.getName());
}
}
In the above example, we have created a Student class which implements the Serializable interface. We have defined two instance variables, id and name, and provided getters for them. In the main method, we have created a Student object and serialized it to a file using ObjectOutputStream. We have then read the object from the file using ObjectInputStream and printed the values of its instance variables.
Serialization is used in many applications such as saving the state of an object between different runs of an application, transmitting objects between different applications or over a network, and storing objects in a database.