Nearby lessons
58 of 125Java - Serialization
📌 What You Will Learn
- What a stream is and how data flows
- Byte streams vs character streams
- Reading and writing text files easily
- The modern File methods and Scanner input
- Serialization — saving an object to a file
Serialization is a core concept of the Java language. This lesson explains Serialization — Save an Object to a File and Object Streams — Serialization Tools with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Serialization — Save an Object to a File
Serialization converts an object into bytes so it can be saved to a file or sent over a network. Later, deserialization reads those bytes back into a live object.
Trainer's Note: Use the transient keyword on fields you do NOT want to save (like passwords): transient String password;. And the class must implement Serializable (a marker interface — it has no methods, it just gives permission to be serialized).
In simple words: Serialization saves an object as bytes and deserialization reads it back. The class must implement the marker interface Serializable, and any field marked transient is skipped during saving.
Example01
Object Streams — Serialization Tools
To save whole objects (serialization), use ObjectOutputStream to write and ObjectInputStream to read. The class must implement Serializable (see section 12.8).
Example02
📝 Key Takeaways
- A stream is a flow of data: input brings data in, output sends it out.
- Byte streams (InputStream/OutputStream) for images/videos; character streams (Reader/Writer) for text.
- Wrap FileReader in BufferedReader to read text line by line.
- Scanner is the simplest way to read input from the keyboard.
- The File class gives file information; it does not read data.
- Serialization saves objects to files; transient fields are not saved.
- Always close streams — or better, use try-with-resources.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1