Serialization
Learn to convert Java objects into byte streams for storage and transmission using Java’s native serialization mechanism.
Up until now, we have worked with data that disappears once our program ends. If we want to save data, we could write text to a file, but that becomes difficult when we need to save complex objects like a GameCharacter with health, inventory, and stats. We would have to manually convert every field to text and then parse it back later.
Java provides a powerful built-in mechanism called serialization that solves this problem. It allows us to freeze an entire object into a portable stream of bytes, save it to a disk or send it over a network, and thaw it back into a living object later.
What is serialization?
Serialization is the process of converting an object’s state (its fields and values) into a stream of bytes. This byte stream is platform-independent, meaning we can write it to a file on one machine and read it on another, provided both run a compatible Java Virtual Machine (JVM).
The reverse process is called deserialization, where the byte stream is used to reconstruct the object in memory.
The Serializable interface
Not all objects can be serialized. For security and safety, Java requires us to explicitly mark classes that are allowed to be serialized. We do this by implementing the java.io.Serializable interface.
This interface is special because it has no methods. It is a marker interface that acts as a flag for the JVM. If we try to serialize an object that does not implement this interface, Java throws a NotSerializableException.
What gets serialized?
When an object is serialized, the JVM saves the entire object graph. However, there are specific rules about which fields are included:
Serialized: All instance variables (fields) are saved, including primitives ( ...