Java Serialization Example
Write a Java program to serialize and deserialize a Student
object with attributes name, age,
and ID.
Sure! Here's a simple Java program that demonstrates serialization and deserialization of a
Student object with the attributes name , age , and id .
📁 Java Files Involved:
You can keep this in a single file for simplicity, or split it. Here's the single file version:
java
import java.io.*;
// Student class must implement Serializable interface
class Student implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for Serializable
classes
private String name;
private int age;
private String id;
// Constructor
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
// Overriding toString() for printing
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + ", id='" + id + "'}";
}
}
1/3
public class StudentSerializationDemo {
public static void main(String[] args) {
String filename = "student.ser";
// Create a Student object
Student student = new Student("Alice", 20, "S12345");
// Serialize the student object
try (ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(filename))) {
out.writeObject(student);
System.out.println("Serialization successful. Object written to " +
filename);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize the student object
try (ObjectInputStream in = new ObjectInputStream(new
FileInputStream(filename))) {
Student deserializedStudent = (Student) in.readObject();
System.out.println("Deserialization successful. Object read from " +
filename);
System.out.println("Deserialized Student: " + deserializedStudent);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
📝 How to Run:
1. Save the code in a file called StudentSerializationDemo.java
2. Compile it using:
nginx
2/3
javac StudentSerializationDemo.java
3. Run it:
nginx
java StudentSerializationDemo
You'll see console output showing the serialized and deserialized student object.
Want an example where you take input from the user too?
3/3