What is Serialization in Java: Explanation and Example
serialization is the process of converting an object into a sequence of bytes so it can be saved to a file or sent over a network. This allows the object to be easily stored or transferred and later restored by deserialization.How It Works
Serialization in Java works like packing your belongings into a suitcase before a trip. You take all the important parts of an object and convert them into a format (bytes) that can be stored or sent somewhere else. Later, you unpack the suitcase to get your belongings back exactly as they were.
Java uses the Serializable interface to mark objects that can be serialized. When you serialize an object, Java writes its data to a stream of bytes. This stream can be saved to a file or sent over a network. When you want the object back, Java reads the bytes and recreates the original object through deserialization.
Example
This example shows how to serialize and deserialize a simple Java object representing a person.
import java.io.*; class Person implements Serializable { private static final long serialVersionUID = 1L; String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class SerializationExample { public static void main(String[] args) { Person person = new Person("Alice", 30); // Serialize the object try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) { out.writeObject(person); System.out.println("Object has been serialized"); } catch (IOException e) { e.printStackTrace(); } // Deserialize the object try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) { Person deserializedPerson = (Person) in.readObject(); System.out.println("Deserialized object: " + deserializedPerson); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
When to Use
Serialization is useful when you want to save the state of an object to a file or send it over a network to another program or computer. For example, saving user settings, caching data, or sending objects between client and server in distributed applications.
It helps in scenarios like storing game progress, transferring data in web services, or saving objects in databases that support binary data.
Key Points
- Serialization converts an object into bytes for storage or transfer.
- Deserialization restores the object from bytes back to its original form.
- Classes must implement
Serializableto be serialized. - Transient fields are not saved during serialization.
- Serialization is commonly used in saving state and communication between systems.