What serialization means
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A student object lives only in memory, so closing the program loses it. To keep it in a file, or send it to another computer, it has to become plain bytes first, and later come back as an object.
Serialization: objects to bytes and back
Serialization turns an object into bytes so it can be saved or sent; deserialization rebuilds the object from those bytes.
Serialization writes an object's class name and field values as bytes; deserialization reads the bytes and creates a fresh object from them. Together they let an object outlive the program that made it.
Example 1 · Save a Student to a file and load it back
import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.file.Files;import java.nio.file.Path;
class Student implements Serializable { String name; int roll; int marks;
Student(String name, int roll, int marks) { this.name = name; this.roll = roll; this.marks = marks; }
@Override public String toString() { return name + " (roll " + roll + ") " + marks + " marks"; }}
public class RoundTripDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { Path file = Path.of("student.ser"); Student before = new Student("Priya", 12, 88);
// Object -> bytes in a file try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(file))) { out.writeObject(before); } System.out.println("Saved: " + before);
// Bytes in a file -> a new object Student after; try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(file))) { after = (Student) in.readObject(); } System.out.println("Loaded: " + after); System.out.println("Same object? " + (before == after));
Files.delete(file); }}Saved: Priya (roll 12) 88 marks Loaded: Priya (roll 12) 88 marks Same object? false
What this code does
writeObject(before)turns theStudentinto bytes instudent.ser;readObject()builds a newStudentfrom those bytes.- The loaded object has the same name, roll and marks, but
before == afterisfalse: it is a copy, not the original object. - The program deletes
student.serat the end so it leaves nothing behind.
Think of a game that saves your progress. The GameState object lives in memory while you play. When you quit, the game serializes it to a file. Next time, it deserializes the file and you continue from the same level. The object you get back is a new object with copied values. It is equal in content, but it is not the same object in memory, so == gives false.
.ser file in Notepad and read it, and only Java programs that have the same class can read it back.The Serializable marker interface
Serializable (in java.io) is a marker interface: an interface with no methods at all. A class writes implements Serializable only to say "Java may save objects of this class".
Example 2 · Without Serializable, writeObject fails
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.NotSerializableException;import java.io.ObjectOutputStream;import java.io.Serializable;
class PlainTicket { String pnr = "4521876390";}
class SavableTicket implements Serializable { String pnr = "4521876390";}
public class MarkerDemo { static void trySave(Object ticket) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { out.writeObject(ticket); System.out.println(ticket.getClass().getSimpleName() + ": saved"); } catch (NotSerializableException e) { System.out.println(ticket.getClass().getSimpleName() + ": " + e); } }
public static void main(String[] args) throws IOException { System.out.println(new PlainTicket() instanceof Serializable); System.out.println(new SavableTicket() instanceof Serializable); trySave(new PlainTicket()); trySave(new SavableTicket()); }}false true PlainTicket: java.io.NotSerializableException: PlainTicket SavableTicket: saved
What this code does
PlainTicketdoes not implementSerializable, soinstanceof SerializableisfalseandwriteObjectthrowsNotSerializableException.- The exception text is
java.io.NotSerializableException: PlainTicket: the message is just the class name that could not be saved. SavableTicketis the same class withimplements Serializableadded, and it saves without any other change.
Java checks this mark when you try to save an object. If the class does not have it, writeObject throws NotSerializableException, and the exception message is the class name. This is a safety rule: a class is not saved unless its author agreed to it. There is nothing to implement. Adding the two words is enough for simple classes whose fields are numbers, Strings and other serializable values.
writeObject with ObjectOutputStream
ObjectOutputStream is an output stream that can write whole objects. You wrap it around any byte stream, for example Files.newOutputStream(file), and call writeObject(obj).
Example 3 · Write a fee receipt and look at the bytes
import java.io.IOException;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
class FeeReceipt implements Serializable { String receiptNo; String student; int amount; // whole rupees
FeeReceipt(String receiptNo, String student, int amount) { this.receiptNo = receiptNo; this.student = student; this.amount = amount; }}
public class WriteReceiptDemo { public static void main(String[] args) throws IOException { Path file = Path.of("receipt.ser"); FeeReceipt r = new FeeReceipt("R-1043", "Arjun", 45000);
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(file))) { out.writeObject(r); }
byte[] bytes = Files.readAllBytes(file); System.out.println("Saved to " + file.getFileName()); System.out.printf("First two bytes: %02X %02X%n", bytes[0], bytes[1]); System.out.println("Contains the class name? " + new String(bytes, StandardCharsets.ISO_8859_1).contains("FeeReceipt"));
Files.delete(file); }}Saved to receipt.ser First two bytes: AC ED Contains the class name? true
What this code does
- Try-with-resources closes the
ObjectOutputStream, which flushes the bytes and closes the file. - Every serialization stream starts with the bytes
AC ED.%02Xprints a byte as two hex digits. - The class name
FeeReceiptis stored inside the file, which is why the reader needs the same class to rebuild the object.
Open it in try-with-resources so the file is closed even when writing fails. writeObject can throw IOException, so the method must catch it or declare throws IOException. The bytes always start with the two bytes AC ED, a fixed "magic number" that marks Java serialization data. After that come the class name, the field names and types, and then the values.
Order of execution
Saving an object, step by step
Tap the steps in the order the program does them.
readObject with ObjectInputStream and the cast
ObjectInputStream reads the bytes back, and its readObject() returns the next object in the stream. Its return type is Object, so you cast it to the real type: Student s = (Student) in.readObject();.
Example 4 · Read several objects in the order they were written
import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.file.Files;import java.nio.file.Path;
class FeeReceipt implements Serializable { String receiptNo; String student; int amount;
FeeReceipt(String receiptNo, String student, int amount) { this.receiptNo = receiptNo; this.student = student; this.amount = amount; }
@Override public String toString() { return receiptNo + " " + student + " Rs " + amount; }}
public class ReadReceiptsDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { Path file = Path.of("receipts.ser");
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(file))) { out.writeObject("Hostel fees, July"); // 1st: a String out.writeObject(new FeeReceipt("R-1043", "Arjun", 45000)); // 2nd out.writeObject(new FeeReceipt("R-1044", "Meena", 42000)); // 3rd }
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(file))) { Object first = in.readObject(); System.out.println("readObject returned a " + first.getClass().getSimpleName());
String title = (String) first; FeeReceipt a = (FeeReceipt) in.readObject(); FeeReceipt b = (FeeReceipt) in.readObject();
System.out.println(title); System.out.println(a); System.out.println(b); System.out.println("Total: Rs " + (a.amount + b.amount)); }
Files.delete(file); }}readObject returned a String Hostel fees, July R-1043 Arjun Rs 45000 R-1044 Meena Rs 42000 Total: Rs 87000
What this code does
readObject()returnsObject;getClass()shows the real type of what came back, hereString.- Each cast matches what was written at that position: first the
String, then twoFeeReceiptobjects. - After the cast you use the object normally, for example adding the two amounts (whole rupees).
Example 5 · Mistake: reading in the wrong order
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class Score implements Serializable { String player; int runs;
Score(String player, int runs) { this.player = player; this.runs = runs; }}
public class WrongOrderDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject("Final match"); out.writeObject(new Score("Rohit", 74)); } byte[] bytes = buffer.toByteArray();
// Bug: reads in the wrong order try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Score s = (Score) in.readObject(); System.out.println(s.player); } catch (ClassCastException e) { System.out.println("Wrong order: " + e.getMessage()); }
// Fix: read in the same order as written try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { String match = (String) in.readObject(); Score s = (Score) in.readObject(); System.out.println(match + ": " + s.player + " " + s.runs); } }}Wrong order: class java.lang.String cannot be cast to class Score (java.lang.String is in module java.base of loader 'bootstrap'; Score is in unnamed module of loader 'app') Final match: Rohit 74
What this code does
- The first object in the stream is a
String, so casting it toScorethrowsClassCastException. The message names both classes. - The fix reads in exactly the order the objects were written:
String, thenScore. ByteArrayOutputStreamandByteArrayInputStreamkeep the bytes in memory, which is handy for quick tests without a file.
readObject can throw IOException and also ClassNotFoundException. That checked exception means the bytes name a class that this program does not have, for example a file saved by another app.
- Objects come back in the same order they were written (write order = read order), so treat the file like a queue. Read them in a different order and the cast fails with
ClassCastException. - To store several objects, write a count first with
writeInt, then loop. - Reading past the last object throws
EOFException.
Next step
Check your understanding
12 quick questions