Java Serialization
java serialization deserialization Serializable serialVersionUID transient ObjectOutputStream ObjectInputStream
Learning Objectives
After completing this lesson, you will be able to:
- Understand Serialization and Deserialization
- Learn why Serialization is important
- Implement the
Serializableinterface - Use
ObjectOutputStreamandObjectInputStream - Understand
serialVersionUID - Use the
transientkeyword - Customize Serialization
- Understand Serialization internals
- Learn Serialization security risks
- Compare Java Serialization with JSON
- Use Serialization in enterprise applications
- Follow Best Practices
- Prepare for Java Interview Questions
Introduction
Imagine you have an Employee object in memory.
Employee employee =new Employee(101,"Rahul",85000);
When the application stops, this object disappears because it exists only in JVM memory.
But what if you want to:
- Save it to a file?
- Send it over a network?
- Cache it?
- Store it in Redis?
- Transfer it to another JVM?
- Persist session information?
Java provides Serialization.
Serialization converts an object into a sequence of bytes so it can be stored or transmitted.
Later, those bytes can be converted back into the original object using Deserialization.
What is Serialization?
Serialization is the process of converting a Java object into a byte stream.
Java Object↓Serialization↓Byte Stream↓File / Network / Database / Cache
What is Deserialization?
Deserialization is the reverse process.
Byte Stream↓Deserialization↓Java Object
Why Serialization?
Serialization is widely used in enterprise systems.
Examples
- Session Replication
- Distributed Systems
- RMI
- JMS
- Object Caching
- File Storage
- Network Communication
- Message Queues
Java Serialization Architecture
Java Object│ObjectOutputStream│Byte Stream│File / Socket / Database│ObjectInputStream│Java Object
Serializable Interface
To make a class serializable, implement the marker interface Serializable.
import java.io.Serializable;public class Employeeimplements Serializable{private int id;private String name;}
Serializable is a marker interface—it contains no methods.
Serializing an Object
Employee employee =new Employee(101,"Rahul");ObjectOutputStream output =new ObjectOutputStream(new FileOutputStream("employee.ser"));output.writeObject(employee);output.close();
This writes the object to the file employee.ser.
Deserializing an Object
ObjectInputStream input =new ObjectInputStream(new FileInputStream("employee.ser"));Employee employee =(Employee)input.readObject();System.out.println(employee);input.close();
Complete Example
public class Employeeimplements Serializable{private int id;private String name;public Employee(int id,String name){this.id = id;this.name = name;}@Overridepublic String toString(){return id + " " + name;}}
Output after deserialization
101 Rahul
serialVersionUID
Every serializable class has a version identifier.
private static final longserialVersionUID = 1L;
Purpose
- Version Control
- Compatibility Checking
- Prevent Invalid Deserialization
Why serialVersionUID?
Suppose Version 1
class Employee{int id;}
Later
class Employee{int id;String department;}
Without a matching serialVersionUID, deserialization may fail with an InvalidClassException.
transient Keyword
Sometimes certain fields should not be serialized.
Example
public class Employeeimplements Serializable{private String name;private transient String password;}
Serialization
name✔ Storedpassword✘ Ignored
After deserialization
System.out.println(employee.getPassword());
Output
null
Use transient for:
- Passwords
- OTPs
- API Keys
- Authentication Tokens
- Temporary Data
static Fields
Static fields belong to the class, not the object.
private static int counter;
Static fields are not serialized.
Custom Serialization
Override writeObject().
private void writeObject(ObjectOutputStream out)throws IOException{out.defaultWriteObject();}
Custom Deserialization
Override readObject().
private void readObject(ObjectInputStream in)throws IOException,ClassNotFoundException{in.defaultReadObject();}
Useful for validation, encryption, or backward compatibility.
Object Graph Serialization
If an object references another serializable object, the entire object graph is serialized.
class Employeeimplements Serializable{Address address;}
Address must also implement Serializable.
Serialization Memory Diagram
Employee Object│├── id├── name└── Address│├── city└── state↓Byte Stream
Serialization Process
Java Object↓Serializable Check↓ObjectOutputStream↓Byte Stream↓Storage
Deserialization Process
Byte Stream↓ObjectInputStream↓Class Loading↓Object Creation↓Field Restoration
Serialization Exceptions
Common exceptions
- NotSerializableException
- InvalidClassException
- ClassNotFoundException
- IOException
- EOFException
Always handle these appropriately.
Serialization in Spring Boot
Serialization is used for
- HTTP Sessions
- Redis Cache
- Distributed Sessions
- Messaging
- Event Processing
However, modern Spring Boot applications often prefer JSON or Protocol Buffers for service-to-service communication instead of native Java Serialization.
Java Serialization vs JSON
| Java Serialization | JSON |
|---|---|
| Binary Format | Text Format |
| Java Specific | Language Independent |
| Smaller Size | More Readable |
| Faster in some JVM-only scenarios | Easier Integration |
| Security Concerns | Widely Used in REST APIs |
Serialization Security
Native Java Serialization can be dangerous if deserializing untrusted data.
Potential risks
- Remote Code Execution
- Gadget Chains
- Object Injection
- Denial of Service
Never deserialize data from an untrusted source without proper validation or filtering.
Best Practices
Always Declare serialVersionUID
Provides explicit version control.
Use transient for Sensitive Data
Examples
- Passwords
- Secrets
- Tokens
Prefer JSON for APIs
Use libraries like Jackson for REST communication.
Validate During Deserialization
Perform integrity and security checks when reading serialized data.
Use Try-with-Resources
try(ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream("employee.ser"))){out.writeObject(employee);}
Resources close automatically.
Keep Serializable Classes Stable
Frequent structural changes can break compatibility.
Common Mistakes
Forgetting Serializable
class Employee{}
Throws
NotSerializableException
Missing serialVersionUID
May cause version compatibility problems.
Serializing Sensitive Fields
Protect confidential information using transient.
Assuming Static Fields are Serialized
Static members are ignored.
Deserializing Untrusted Data
Never deserialize data from unknown or untrusted sources without safeguards.
Hands-on Exercise
Create a Java program that:
- Creates an
Employeeclass implementingSerializable. - Serializes an object to a file.
- Deserializes the object.
- Declares
serialVersionUID. - Uses the
transientkeyword. - Demonstrates that static fields are not serialized.
- Implements custom
writeObject(). - Implements custom
readObject(). - Serializes an object graph containing
EmployeeandAddress. - Compares Java Serialization with JSON serialization using Jackson.
Summary
Java Serialization is the mechanism for converting Java objects into byte streams and restoring them later through deserialization. It enables object persistence, session replication, caching, and inter-JVM communication. While Serialization remains important for understanding legacy systems and JVM-specific use cases, modern enterprise applications often prefer JSON, Protocol Buffers, or other language-neutral formats for external communication due to better interoperability and improved security.
Key Takeaways
- Serialization converts objects into byte streams.
- Deserialization reconstructs objects from byte streams.
- Implement the
Serializableinterface to enable serialization. ObjectOutputStreamwrites objects.ObjectInputStreamreads objects.serialVersionUIDcontrols version compatibility.transientexcludes sensitive fields from serialization.- Static fields are not serialized.
- Native Java Serialization should not be used with untrusted data.
- JSON is generally preferred for REST APIs and cross-platform communication.
Professional Interview Questions
1What is Serialization in Java?
Professional Answer
Serialization is the process of converting a Java object into a byte stream so that it can be stored, transferred over a network, or cached. Deserialization reconstructs the original object from the byte stream. Java supports this through the Serializable marker interface and the ObjectOutputStream and ObjectInputStream classes.
Follow-up Questions
- Which interface enables serialization?
- What classes perform serialization and deserialization?
Interview Tip: Object → Byte Stream → Object.
2What is the purpose of serialVersionUID?
Professional Answer
serialVersionUID is a version identifier for a serializable class. During deserialization, the JVM verifies that the sender and receiver of a serialized object have compatible class definitions. Declaring an explicit serialVersionUID helps maintain version compatibility and prevents unexpected InvalidClassException errors when class definitions evolve.
Follow-up Questions
- What happens if serialVersionUID changes?
- Should you always declare it explicitly?
Interview Tip: serialVersionUID = Version Number for Serialized Objects.
3Why is native Java Serialization discouraged for modern distributed applications?
Professional Answer
Native Java Serialization is Java-specific, can expose applications to deserialization security vulnerabilities if untrusted data is processed, and is not interoperable with other programming languages. Modern distributed systems typically use JSON, Protocol Buffers, Avro, or similar serialization formats because they are language-independent, easier to version, and more suitable for APIs and microservices.
Follow-up Questions
- Why do REST APIs commonly use JSON instead?
- What security risks are associated with Java Serialization?
Interview Tip: Java Serialization → JVM-to-JVM / Legacy Use Cases, JSON / Protobuf → Modern Microservices & REST APIs.