How to Serialize Object in Java: Simple Guide with Example
To serialize an object in Java, make the class implement the
Serializable interface and use ObjectOutputStream to write the object to a file or stream. This process converts the object into bytes so it can be saved or sent and later restored by deserialization.Syntax
Serialization in Java requires the class to implement the Serializable interface, which is a marker interface (it has no methods). Then, use ObjectOutputStream to write the object to an output stream.
- Serializable interface: Marks the class as serializable.
- ObjectOutputStream: Writes the object to a stream.
- FileOutputStream: Connects the stream to a file.
java
import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.FileOutputStream; public class MyClass implements Serializable { private static final long serialVersionUID = 1L; // class fields and methods } // Serialization syntax try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.ser"))) { out.writeObject(myObject); }
Example
This example shows how to serialize a simple Person object to a file named person.ser. It demonstrates implementing Serializable, creating an object, and writing it to a file.
java
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 SerializeExample { public static void main(String[] args) { Person person = new Person("Alice", 30); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) { out.writeObject(person); System.out.println("Serialization successful: " + person); } catch (IOException e) { e.printStackTrace(); } } }
Output
Serialization successful: Person{name='Alice', age=30}
Common Pitfalls
- Forgetting to implement
SerializablecausesNotSerializableException. - Not declaring
serialVersionUIDcan lead to compatibility issues during deserialization. - Trying to serialize objects with non-serializable fields without marking them
transientcauses errors. - Not closing streams properly can cause resource leaks.
java
import java.io.Serializable; /* Wrong: Class does not implement Serializable */ class WrongClass { int data; } /* Right: Implements Serializable */ class RightClass implements Serializable { private static final long serialVersionUID = 1L; int data; } /* Non-serializable field example */ class Example implements Serializable { private static final long serialVersionUID = 1L; transient Thread thread; // transient avoids serialization error }
Quick Reference
Remember these key points when serializing objects in Java:
- Implement
Serializableinterface in your class. - Use
ObjectOutputStreamto write objects to streams. - Declare
serialVersionUIDfor version control. - Mark non-serializable fields as
transient. - Always close streams using try-with-resources.
Key Takeaways
Implement the Serializable interface to enable object serialization.
Use ObjectOutputStream with a FileOutputStream to write objects to files.
Declare serialVersionUID to maintain serialization compatibility.
Mark fields that should not be serialized as transient.
Always close streams properly to avoid resource leaks.