Showing posts with label Deserialization. Show all posts
Showing posts with label Deserialization. Show all posts

Tuesday, February 24, 2026

What is Serialization and Deserialization in Java?

Serialization and Deserialization are mechanisms in Java used to convert objects into a transferable or storable format and then rebuild them back into objects.




🔹 Serialization

Serialization is the process of converting a Java object into a byte stream so it can be:

  • Stored in a file

  • Sent across a network

  • Cached or saved in databases

👉 Object → Byte Stream

Example

import java.io.*;

class Student implements Serializable {
    int id;
    String name;

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

public class SerializeDemo {
    public static void main(String[] args) throws Exception {
        Student s1 = new Student(101, "Rahul");

        FileOutputStream fileOut = new FileOutputStream("student.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);

        out.writeObject(s1); // Serialization
        out.close();
    }
}

🔹 Deserialization

Deserialization is the reverse process where the byte stream is converted back into the original Java object.

👉 Byte Stream → Object

Example

import java.io.*;

public class DeserializeDemo {
    public static void main(String[] args) throws Exception {
        FileInputStream fileIn = new FileInputStream("student.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);

        Student s2 = (Student) in.readObject(); // Deserialization
        in.close();

        System.out.println(s2.name);
    }
}

🔹 Important Points

  • Class must implement Serializable interface.

  • Serializable is a marker interface (no methods).

  • transient keyword prevents fields from being serialized.

  • Commonly used in distributed systems, APIs, and session management.


🔹 Key Differences



✅ Promotional Content

To master Java concepts like serialization, JVM internals, collections, and real-time backend development with practical implementation, join the Top Java Real Time Projects Online Training in Ameerpet.

Thread vs Runnable in Java: Key Differences, Best Practices & Which One to Use (2026 Guide)

Multithreading is a core part of Java —but one of the most common interview questions is: Should you use Thread or Runnable ? Thread is a ...