Serialization and Deserialization
import java.io.*;
class Student implements Serializable {
private String name;
private int rollNumber;
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}
}
public class SerializationExample {
public static void main(String[] args) {
Student student = new Student("Alice", 123);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
oos.writeObject(student);
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}Last updated