Java Serialization
What Is Serialization?
Java serialization transforms an object into a byte stream which allows it to be saved or transferred.
- Saved to a file
- Sent over a network
- Stored in memory or a database
Deserialization works in the opposite direction by turning a byte stream into its original object structure.

Why Use Serialization?
- Save the object state to a file or database.
- You can move objects across different JVMs and across network systems.
- Use cache objects within messaging systems such as RMI and sockets.
Enabling Serialization
Implement Serializable Interface
import java.io.Serializable;
public class Student implements Serializable {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Serializable is a marker interface — no methods to implement.
Serialize the Object
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Student s1 = new Student(101, "Anand");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
oos.writeObject(s1);
System.out.println("Object serialized.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Deserialize the Object
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student s = (Student) ois.readObject();
System.out.println("Deserialized Student: " + s.id + ", " + s.name);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| Feature | Description |
|---|---|
| Interface | java.io.Serializable |
| Type | Marker Interface |
| Super Interface | None |
| Methods | None |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com