×

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 Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.