×

Java Serialization

JAVA SERIALIZATION

Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in that objects.

We can write that object in a file and then it can be read and deserialized.

We retrieve the information from bytes and can recreate the object in the memory.

The most powerful feature is that the whole process is independent from JVM. This means that an object can be serialized form one machine and can be deserialized to another machine.

ObjectInputStream and ObjectOutputStream contains the methods for serialization and deserialization.

Important methods are:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and then sends it to the output stream. Similarly, the ObjectInputStream class has  the method for deserializing an object

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so we will need to cast it to its appropriate datatype.

The class that implements  java.io.Serializable interface can be serialized and those fields which are marked transient cannot be serialized.

Example:

Person Class

public class Person implements Serializable {
private static final long serialVersionUID = -3216968774585522982L;
int age;
String Address;
public Person(){
System.out.println("Person Class constructor called");
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public Person(int age, String address) {
this.age = age;
this.Address = address;
}
}

Employee Class

public class Employee extends Person implements Serializable  {
private static final long serialVersionUID = -2892927121614640166L;
private String name;
public Employee(String name2, int id2, int salary2) {
super(5, "Delhi");
System.out.println("Employee Class constructor called");
this.id= id2;
this.name= name2;
this.salary= salary2;
}
private int id;
transient private int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", salary=" + salary + ", age="+this.age +",address="+this.Address +"]";
}
}

Main Class

public class SerializationTest {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
String filename = "Employee.txt"; // make file named "Employee.txt" in the current working directory.
Employee e = new Employee("Raj",5,5000);
System.out.println(e);
// save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
System.out.println("Serialization process begins");
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(e);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// read the object from file
// save the object to file
System.out.println("Deserialization process begins");
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
e = (Employee) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(e);
}
}

Output:

Working Directory = /home/pardeep/NK/Work/Project/JavaTest
Employee Class constructor called
Employee [name=Raj, id=5, salary=5000, age=5,address=Patna]
Serialization process begins
Deserialization process begins
Employee [name=Raj, id=5, salary=0, age=5,address=Patna]

The readObject method may throw a ClassNotFoundException so we have to insert in try/catch block. JVM have to find the bytecode for the class in order to deserialize an object. If JVM can't find a class during the deserialization of an object the ClassNotFoundException is thrown.


Related Topics

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.