Externalizable Serialization Example

This program demonstrates using Externalizable interface for serialization.

Problem Statement

Write a Java program that serializes and deserializes a Student object using Externalizable.

Source Code

1 import java.io.*;
2 class Student implements Externalizable {
3 int id; String name;
4 public Student(){}
5 public Student(int id,String name){ this.id=id; this.name=name; }
6 public void writeExternal(ObjectOutput out) throws IOException {
7 out.writeInt(id); out.writeObject(name);
8 }
9 public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
10 id=in.readInt(); name=(String)in.readObject();
11 }
12 }
13 public class ExternalizableExample {
14 public static void main(String[] args) throws Exception {
15 System.out.println("Eduinq Externalizable Example");
16 ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("student.ser"));
17 Student s=new Student(1,"Arun");
18 oos.writeObject(s); oos.close();
19 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("student.ser"));
20 Student s2=(Student)ois.readObject();
21 System.out.println("Eduinq Student: "+s2.id+" "+s2.name);
22 }
23 }

Program Output

					Eduinq Externalizable Example
Eduinq Student: 1 Arun
				

Explanation

Implements Externalizable for custom control. - Explicitly writes and reads fields. - Exception handling ensures safe operations. - In enterprise systems, Externalizable optimizes serialization. Conclusion: Shows using Externalizable interface.

Quick Links to Explore