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 [Link].*;
// 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) {
[Link] = name;
[Link] = age;
[Link] = 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 = "[Link]";
// Create a Student object
Student student = new Student("Alice", 20, "S12345");
// Serialize the student object
try (ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(filename))) {
[Link](student);
[Link]("Serialization successful. Object written to " +
filename);
} catch (IOException e) {
[Link]();
}
// Deserialize the student object
try (ObjectInputStream in = new ObjectInputStream(new
FileInputStream(filename))) {
Student deserializedStudent = (Student) [Link]();
[Link]("Deserialization successful. Object read from " +
filename);
[Link]("Deserialized Student: " + deserializedStudent);
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
}
}
📝 How to Run:
1. Save the code in a file called [Link]
2. Compile it using:
nginx
2/3
javac [Link]
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