×

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

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.