How Does Java Handle Serialization and Deserialization?

·

How Does Java Handle Serialization and Deserialization?

Serialization converts objects to byte streams for storage or transmission.

Deserialization

Deserialization reconstructs objects from byte streams.

Example Code


            import java.io.*;

            class Person implements Serializable {
                String name;
                int age;
                Person(String name, int age) {
                    this.name = name;
                    this.age = age;
                }
            }

            // Serialization
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(new Person("John Doe", 30));
            out.close();
            fileOut.close();

            // Deserialization
            FileInputStream fileIn = new FileInputStream("person.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Person p = (Person) in.readObject();
            in.close();
            fileIn.close();
            

This example demonstrates Java’s serialization and deserialization process.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *