Introduction to Serialization in Java
Serialization in Java is a mechanism that converts an object’s state into a byte stream. Deserialization is its reverse process. Through deserialization, from a byte stream, an actual Java object is created in the memory. Such a mechanism persists the object. The byte stream so created from serialization does not depend on any platform. The object serialized on one platform can be deserialized on any other platform without any issue.
Thus, the entire process of serialization and deserialization is JVM independent. If a class object is to be serialized, then one needs to implement the java.io.Serializable interface. Serializable in java is a marker interface. It has no fields or methods to implement. A class is made serializable by this process which looks like an Opt-In process. Serialization in Java is implemented by the two classes ObjectInputStream and ObjectOutputStream. All that is required is a wrapper over them so that they can be saved to file or can be sent over a network.
Concept of Serialization in Java
The class ObjectOutputStream, a serialization class mentioned in the above section, contains several writing methods for writing various data types, but one method is the most popular.
public final void writeObject( Object x ) throws IOException
The above method can be used to serialize an Object. This method also sends it to the output stream. In the same way, ObjectInputStream class contains the method for object deserializing.
public final Object readObject() throws IOException, ClassNotFoundException
The deserialization method retrieves the object from a stream and deserializes the same. The return value is again an object, so all that is needed is to cast it to a relevant data type.
For a class to be serialized successfully, there are two conditions that must be met:
- io. The class must implement a serializable interface.
- All fields of the class must be serializable. If even one field is not serializable, then it should be marked transient.
If someone needs to check if a class is serializable or not, the simple solution is to check if the class implements the java.io.Serializable method; if it does, then it is serializable. If it not, then it’s not. One should notice that when serializing an object to a file, the standard practice is to give the file a .ser extension.
Methods
If these methods are present in the class, they are used for serialization in Java purposes.
Method of Serialization in Java
Method | Description |
public final void writeObject (Object obj) throws IOException {} | This will write the specified object to the ObjectOutputStream. |
public void flush() throws IOException {} | This will flush the current output stream. |
public void close() throws IOException {} | This will close the current output stream. |
Method of Deserialization in Java
Method | Description |
public final Object readObject() throws IOException, ClassNotFoundException{} | This will read an object from the input stream. |
public void close() throws IOException {} | This will close ObjectInputStream. |
Example of Serialization in Java
Given below are the examples mentioned:
An example in Java is provided here to demonstrate how serialization works in Java. We create an Employee class to study some features, and the code for the same is provided below. This employee class implements the Serializable interface.
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a letter to " + name + " " + address);
}
}
When this program is done with executing, a file named employee.ser would be created. This program does not provide a guaranteed output, rather it is for explanatory purposes only, and the objective is to understand its use and to work.
import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Rahul Jain";
e.address = "epip, Bangalore";
e.SSN = 114433;
e.number = 131;
try {
FileOutputStream fileOut =
new FileOutputStream("https://cdn.educba.com/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
The below described DeserializeDemo program deserializes the above Employee object created in the Serialize Demo program.
import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("https://cdn.educba.com/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class is not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
Output:
Deserialized Employee…
Name: Rahul Jain
Address: epip, Bangalore
SSN: 0
Number:131
Some important points related to the program above are provided below:
- The try/catch block above tries to catch a ClassNotFoundException. This is declared by the readObject() method.
- A JVM can deserialize an object only if it finds the bytecode for the class.
- If the JVM does not find a class during the deserialization, it will throw ClassNotFoundException.
- The return value of readObject() is always cast to an Employee reference.
- SSN field value was 114433 initially when the object was serialized, but this value was not sent to the output stream. Because of the same, the deserialized Employee SSN field object is 0.
Conclusion
Above, we introduced serialization concepts and provided examples. Let’s understand the need for serialization in our concluding remarks.
- Communication: If two machines that are running the same code need to communicate, the easy way out is that one machine should build an object containing information that it would transmit and then serialize that object before sending it to the other machine. Not a great method, but it gets the job done.
- Persistence: If the state of operation is to be stored in a database, it is first serialized to a byte array and then stored in the database for retrieval at a later point in time.
- Deep Copy: If an exactreplica of an Object needs to be created and writing a specialized clone class is too much hard work, then only serializing the object and then de-serializing it to another object will achieve the goal.
- Cross JVM Synchronization: Different JVMs running on different machines and architectures can be synchronized.
Recommended Articles
This has been a guide to Serialization in Java. Here we have discussed the basic concept, different methods of serialization in java with examples. You may also look at the following article to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses