Serialization and Deserialization in Java
×


Serialization and Deserialization in Java

254

๐Ÿ—‚๏ธ What is Serialization and Deserialization in Java?

Serialization in Java is the process of converting an object into a byte stream, allowing it to be saved to a file or sent over a network. Deserialization is the reverse process, where the byte stream is converted back into a copy of the original object.

These processes help in object persistence, deep copying, and communication between Java programs.

โ“ Why use Serialization and Deserialization?

Serialization is useful when you want to store the state of an object or transmit it. For example, saving user session data to disk or sending objects over a network in distributed systems.

Deserialization restores the object's state so the program can continue using it.

๐Ÿ“ How to make a Class Serializable

To enable serialization, a class must implement the Serializable interface. This is a marker interface, which means it doesn't require any methods to be implemented but tells Java that the class supports serialization.

import java.io.Serializable;

public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    // Getters and setters omitted for brevity
}

๐Ÿ’พ Serialization Example

This example demonstrates how to serialize an object of the Employee class to a file.

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeExample {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 101);

        try (FileOutputStream fos = new FileOutputStream("employee.ser");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(emp);
            System.out.println("Object serialized successfully");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

๐Ÿ“‚ Deserialization Example

This example shows how to read the serialized object back into memory.

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializeExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("employee.ser");
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            Employee emp = (Employee) ois.readObject();
            System.out.println("Employee Name: " + emp.getName());
            System.out.println("Employee ID: " + emp.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

๐Ÿ”’ Using the transient Keyword

Sometimes, you may want to exclude some fields from serialization, for example, sensitive data like passwords. You can mark these fields with the transient keyword to prevent them from being serialized.

public class User implements Serializable {
    private String username;
    private transient String password; // will not be serialized

    // constructor, getters, setters
}

โš ๏ธ Important Points to Remember

  • Classes must implement Serializable to support serialization.
  • serialVersionUID is a unique identifier used during deserialization to verify compatibility.
  • Transient fields are not serialized.
  • Serialization can throw NotSerializableException if a non-serializable object is referenced.

โœ… Conclusion

Serialization and Deserialization in Java are powerful features that make object persistence and data transfer simple and efficient. Understanding these concepts is crucial for Java developers working with file I/O, networking, or distributed systems.



If youโ€™re passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ€“ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat