Exploring Serialization and Deserialization in Java
Pratyush Kumar Sahu
Java Developer @ Tejosma Tech | Best Student Awardee | Software Developer | Java | DSA | J2EE | Servlets | Spring Boot | Microservices | Web Services | JPA | Hibernate
Introduction
In Java,?Serialization?is the process of converting an object’s state to a byte stream, and?Deserialization?is the process of reconstructing the object from the byte stream. This mechanism is used in networking programming and distributed applications.
What is Serialization?
Serialization is the process of converting an object’s state, including its byte code, into a byte stream. This byte stream can then be saved to a file or sent over a network.
Java
import java.io.*;
class Demo implements Serializable {
public int a;
public String b;
public Demo(int a, String b) {
this.a = a;
this.b = b;
}
}
What is Deserialization?
Deserialization is the reverse process of serialization where we can get the object back from the byte stream. This is used when we want to use the object again.
Why Use Serialization and Deserialization?
Serialization and deserialization are typically used in situations where you need to ‘flatten’ an object into a format that can be stored or transmitted and then recreate it. Some common use cases include:
·???????? Storing data in an object-oriented way.
领英推荐
·???????? Sending data over a network.
·???????? Caching data for later use.
How to Serialize and Deserialize an Object in Java
Here’s a simple example of how to serialize and deserialize an object in Java:
JAVA
public class Test {
public static void main(String[] args) {
Demo object = new Demo(1, "serialization-demo");
String filename = "file.ser";
// Serialization
try {
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized");
} catch(IOException ex) {
System.out.println("IOException is caught");
}
Demo object1 = null;
// Deserialization
try {
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
object1 = (Demo)in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized ");
System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
} catch(IOException ex) {
System.out.println("IOException is caught");
} catch(ClassNotFoundException ex) {
System.out.println("ClassNotFoundException is caught");
}
}
}
Conclusion
Serialization and de-serialization in Java are powerful concepts that allow us to convert an Object’s state into a byte stream, and to bring it back to life at a later time or in a different JVM. It’s a fundamental concept in Java that’s used in many high-level technologies.
Remember, with great power comes great responsibility. Always be mindful of what you’re serializing, as it can have both performance and security implications.
Happy coding!
?