Java
Serialization
Object serialization and deserialization.
By EZ4Code Team
serializationserialize
Code
import java.io.*;
class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private transient String password; // Not serialized
public User(String name, String password) {
this.name = name;
this.password = password;
}
}
// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("user.dat"))) {
oos.writeObject(new User("Alice", "secret"));
}
// Deserialize
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("user.dat"))) {
User user = (User) ois.readObject();
System.out.println(user.name); // Alice
// password is null (transient)
}Explanation
The Serializable interface marks serializable classes; transient fields are excluded from serialization.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.