Serialization and Deserialization :
Serialization is the process of converting an object into a byte stream, which can be stored in a file or sent over a network. This byte stream contains the object's data as well as information about the object's type and structure.
Deserialization, on the other hand, is the process of converting the byte stream back into an object. During deserialization, the byte stream is read and used to recreate the original object with its data and structure intact.
Goal of Serialization :
The primary goal of serialization is to persist an object's state so that it can be saved to a file, sent over a network, or otherwise transported from one application to another.
Goal of Deserialization :
The goal of deserialization is to recreate an object from its serialized form. This allows the object to be restored to its original state, enabling applications to work with the data it represents.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
When We Use Serialization and Deserialization?
Serialization and deserialization are commonly used in scenarios where objects need to be transmitted between different applications or stored persistently. Examples include saving objects to files, sending objects over a network, or caching objects in memory.
Why We Use Serialization and Deserialization?
Serialization and deserialization allow objects to be easily transferred between different applications and platforms. They provide a convenient way to persist object state and facilitate communication between distributed systems.
Note: To make a Java object serializable we implement the java.io.Serializable interface.
Points to remember:
⚫If a superclass implements Serializable, then subclass is automatically serializable.
⚫Static variables are not serialized in java.
⚫The serializable interface in Java is a marker interface. (has no field, method etc... so it is empty)
⚫Transient variables are not serialized in Java.
⚫If a class has a reference of another class, all the data members of that class also get serilized.
serialization project:
Main.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
try {
// Creating an object to serialize
MyClass object = new MyClass("Hello, World!");
// Serializing the object
FileOutputStream file = new FileOutputStream("data.ser"); //Creates a new file and open file for writing (You cannot delete file while it is open)
ObjectOutputStream out = new ObjectOutputStream(file); //Establishing a pipeline for writing serialized Java objects to the file. The data is not yet converted to a byte stream at this point; instead, out is set up to perform this conversion when writeObject is called.
out.writeObject(object); //This line serializes the object "object" (converts the object into a byte stream representation) and writes its serialized form to the file associated with the "ObjectOutputStream" instance "out".
out.close(); //When this line is executed, you can delete the file because the file is closed.
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MyClass.java
import java.io.Serializable;
public class MyClass implements Serializable {
private String message;
public MyClass(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
deserialization project:
Main.java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Deserializing the object
FileInputStream fileIn = new FileInputStream("data.ser"); //Opens the file for reading
ObjectInputStream in = new ObjectInputStream(fileIn); //Establishing a pipeline for reading serialized Java objects from the file. The data is not yet converted to a Java object at this point; instead, in is set up to perform this conversion when readObject is called.
MyClass obj = (MyClass) in.readObject(); //This line reads the serialized object from the file associated with the "ObjectInputStream" instance "in" and deserializes it (converts the byte stream representation back into an object). The object is then cast to the appropriate type.
in.close(); //When this line is executed, you can delete the file because the file is closed.
fileIn.close();
// Using the deserialized object
System.out.println("Message from deserialized object: " + obj.getMessage());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
MyClass.java
import java.io.Serializable;
public class MyClass implements Serializable {
private String message;
public MyClass(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
static-variables-serialization project:
Main.java
import java.io.*;
/**
* Static variables are not serialized in Java.
*/
public class Main {
public static void main(String[] args) {
try {
// Creating an object to serialize
MyClass object = new MyClass();
// Serializing the object
FileOutputStream file = new FileOutputStream("data.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Deserializing the object
FileInputStream fileIn = new FileInputStream("data.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
MyClass obj = (MyClass) in.readObject();
in.close();
fileIn.close();
MyClass.staticMessage = "New Static Abagai is from New Static Khuzait";
// Using the deserialized object
System.out.println("After Deserialization:");
System.out.println("Static Value = " + obj.staticMessage);
System.out.println("Instance Value = " + obj.instanceMessage);
//
// Output:
//
// After Deserialization:
// Static Value = New Static Abagai is from New Static Khuzait
// Instance Value = Instance Abagai is from Instance Khuzait
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
MyClass.java
import java.io.Serializable;
public class MyClass implements Serializable {
public static String staticMessage = "Static Abagai";
public String instanceMessage = "Instance Abagai";
public MyClass() {
this.staticMessage = this.staticMessage + " " + "is from Static Khuzait"; // Modify static value in constructor for demonstration
this.instanceMessage = this.instanceMessage + " " + "is from Instance Khuzait"; // Modify instance value in constructor for demonstration
}
}
transient-variables-serialization project:
Main.java
import java.io.*;
/**
* Transient variables are not serialized.
*/
public class Main {
public static void main(String[] args) {
try {
// Creating an object to serialize
MyClass object = new MyClass("Simge Sağın","Hello, World!");
// Serializing the object
FileOutputStream file = new FileOutputStream("data.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Deserializing the object
FileInputStream fileIn = new FileInputStream("data.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
MyClass obj = (MyClass) in.readObject();
in.close();
fileIn.close();
// Using the deserialized object
System.out.println("Message from deserialized object: " + obj.getMessage() + ", "+obj.getTransientMessage());
// Output: Message from deserialized object: Hello, World!, null
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
MyClass.java
import java.io.Serializable;
public class MyClass implements Serializable {
private transient String transientMessage;
private String message;
public MyClass(String transientMessage ,String message) {
this.transientMessage = transientMessage;
this.message = message;
}
public String getMessage() {
return message;
}
public String getTransientMessage() {
return transientMessage;
}
}
super-class-and-sub-class-serialization-case-1 project:
Main.java
import java.io.*;
/**
* Case 1: If the superclass is serializable, then subclass is automatically serializable
*/
public class Main {
public static void main(String[] args) {
try {
// Creating an object to serialize
MySubClass object = new MySubClass("Super Hello, World!","Sub Hello, World!" );
// Serializing the object
FileOutputStream file = new FileOutputStream("data.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Deserializing the object
FileInputStream fileIn = new FileInputStream("data.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
MySubClass obj = (MySubClass) in.readObject();
in.close();
fileIn.close();
// Using the deserialized object
System.out.println("Superclass field: " + obj.superClassField);
System.out.println("Subclass field: " + obj.subClassField);
// Output:
// Superclass field: Super Hello, World!
// Subclass field: Sub Hello, World!
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
MySuperClass.java
import java.io.Serializable;
public class MySuperClass implements Serializable{
String superClassField;
public MySuperClass(String superClassField) {
this.superClassField = superClassField;
}
}
MySubClass.java
public class MySubClass extends MySuperClass{
String subClassField;
public MySubClass(String superClassField, String subClassField) {
super(superClassField);
this.subClassField = subClassField;
}
}
class-reference-serialization project:
Main.java
import java.io.*;
/**
* If a class has a reference of another class, all the data members of that class also get serilized.
*/
public class Main {
public static void main(String[] args) {
try {
// Creating an object to serialize
Address address = new Address("New York", "NY");
Employee employee = new Employee("John Doe", 30, address);
// Serializing the object
FileOutputStream file = new FileOutputStream("data.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(employee);
out.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Deserializing the object
FileInputStream fileIn = new FileInputStream("data.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee obj = (Employee) in.readObject();
in.close();
fileIn.close();
// Using the deserialized object
System.out.println("Deserialized Employee:");
System.out.println("Name: " + obj.name);
System.out.println("Age: " + obj.age);
System.out.println("City: " + obj.address.city);
System.out.println("State: " + obj.address.state);
//
// Output:
//
// Deserialized Employee:
// Name: John Doe
// Age: 30
// City: New York
// State: NY
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Address.java
import java.io.Serializable;
public class Address implements Serializable {
String city;
String state;
Address(String city, String state) {
this.city = city;
this.state = state;
}
}
Employee.java
import java.io.Serializable;
public class Employee implements Serializable {
String name;
int age;
Address address; // Reference to another serializable class
Employee(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
}
💫The End 💫