×

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

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.