I/O

io5Serialization

Path
pkg9io/io5Serialization.java
Package
pkg9io
Study order
5
Run
Single-file source launch
Command
java pkg9io/io5Serialization.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg9io/io5Serialization.java
1package pkg9io;2 3import java.io.ByteArrayInputStream;4import java.io.ByteArrayOutputStream;5import java.io.IOException;6import java.io.ObjectInputStream;7import java.io.ObjectOutputStream;8import java.io.Serializable;9 10/*11 * io5Serialization.java12 * ---------------------13 * Java object serialization: turning objects into bytes and back.14 *15 * DEFINITION:16 *   Serialization writes an object graph to a byte stream (Serializable);17 *   deserialization reconstructs it. Used for caching, deep copy, and (legacy)18 *   network transfer.19 *20 * KEY POINTS:21 *   - A class must implement Serializable; non-serializable fields need transient.22 *   - serialVersionUID pins the class version for compatibility.23 *   - transient fields are skipped (e.g. secrets, caches, derived data).24 *   - SECURITY: never deserialize untrusted data — prefer JSON for external I/O.25 */26public class io5Serialization {27 28    static class User implements Serializable {29        private static final long serialVersionUID = 1L;     // version contract30        String name;31        int age;32        transient String password;     // NOT serialized (skipped)33 34        User(String name, int age, String password) {35            this.name = name; this.age = age; this.password = password;36        }37        @Override public String toString() {38            return "User{name=" + name + ", age=" + age + ", password=" + password + "}";39        }40    }41 42    public static void main(String[] args) throws IOException, ClassNotFoundException {43        User original = new User("Ada", 36, "s3cr3t");44        System.out.println("Original     : " + original);45 46        // SERIALIZE to a byte array47        ByteArrayOutputStream bytes = new ByteArrayOutputStream();48        try (ObjectOutputStream oos = new ObjectOutputStream(bytes)) {49            oos.writeObject(original);50        }51        System.out.println("Serialized   : " + bytes.size() + " bytes");52 53        // DESERIALIZE back into a new object54        User restored;55        try (ObjectInputStream ois =56                 new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {57            restored = (User) ois.readObject();58        }59        System.out.println("Deserialized : " + restored);60        System.out.println("password lost (transient)? " + (restored.password == null));61        System.out.println("distinct objects (deep copy)? " + (original != restored));62    }63}