Clean • Professional
Java provides Object Streams to perform object-level I/O , meaning you can read/write entire Java objects to files, memory, or network streams. This is the foundation of Serialization & Deserialization.
Object Streams are specialized streams that allow Java objects to be written as bytes and restored back as full objects.
Java provides two main classes:

These classes are part of the java.io package.
To serialize an object:
SerializableserialVersionUID is recommendedObjectOutputStream is used to serialize Java objects and write them into a binary file.
writeObject().Serializable.ObjectInputStream is used to deserialize objects from a file and reconstruct them in memory.
readObject().Below is the full demo with both ObjectOutputStream & ObjectInputStream.
Step 1: Create a Serializable Class
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
}
}
Step 2: Write Object Using ObjectOutputStream (Serialization)
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class WriteObject {
public static void main(String[] args) {
try (ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("student.ser"))) {
Student s1 = new Student(101, "Amit");
oos.writeObject(s1);
System.out.println("Object written successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 3: Read Object Using ObjectInputStream (Deserialization)
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ReadObject {
public static void main(String[] args) {
try (ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("student.ser"))) {
Student s = (Student) ois.readObject();
System.out.println("Read Object: " + s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
serialVersionUID for version control.Class must implement Serializable
class Student implements Serializable { }
Static & transient fields are not serialized
Order of readObject() must match writeObject()
serialVersionUID prevents compatibility issues
Yes, you can write multiple objects:
oos.writeObject(obj1);
oos.writeObject(obj2);
And read:
obj1 = (MyClass) ois.readObject();
obj2 = (MyClass) ois.readObject();
writeObject() → saves objects.readObject() → loads objects..ser file.