Serialization
- Serialization is the process of converting an object into a byte stream, enabling it to be easily saved to a file or transmitted over a network. This allows the object's state to be preserved and later reconstructed.
Deserialization
- Deserialization is the reverse process, where the byte stream is converted back into a Java object. This reconstructs the original object from the serialized data.
❓ How to Serialize an Object in Java:
1. Implement Serializable Interface:
- The class of the object to be serialized must implement the
java.io.Serializable
interface. - Example
```java
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID \= 1L; // Recommended for version control
private String name;
private int age;
// Constructor, getters, and setters
}
```
2. Use ObjectOutputStream:
- Create an instance of
ObjectOutputStream
and write the object to a file or output stream. - Example
```java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializeExample {
public static void main(String[] args) {
User user \= new User("Alice", 30);
try (FileOutputStream fileOut \= new FileOutputStream("user.ser");
ObjectOutputStream out \= new ObjectOutputStream(fileOut)) {
out.writeObject(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
❓ How to Deserialize an Object in Java:
1. Use ObjectInputStream:
- Create an instance of
ObjectInputStream
and read the object from the file or input stream. - Example
```java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeExample {
public static void main(String[] args) {
User user \= null;
try (FileInputStream fileIn \= new FileInputStream("user.ser");
ObjectInputStream in \= new ObjectInputStream(fileIn)) {
user \= (User) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
// Use the deserialized object
System.out.println("Name: " + user.getName() + ", Age: " + user.getAge());
}
}
```