What is serialization and deserialization in java?

Serialization:-Serialization is the conversion of object to a series of byte so that object can be easily save to persistent storage across a communication link.
From serialization we can write object into file. All process is JVM independent means an object can be serialized on one platform and deserialized on an entirely different platform.
Its available in java.io package.

				
					import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Test implements Serializable {
	int i;
	int j;

	public Test(int i, int j) {
		this.i = i;
		this.j = j;
	}
}

public class HelloSerial {
	public static void main(String[] args) throws Exception {
		
		Test t1 = new Test(20, 30);
		FileOutputStream fs = new FileOutputStream("abc.ser");
		ObjectOutputStream os = new ObjectOutputStream(fs);
		os.writeObject(t1);
		os.flush();
		System.out.println("object is written inside file");
	}
}

				
			

Deserialization :-
It is reverse operation of serialization. Deserialization is the process of read object from file in serializable state.

				
					import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class HelloDeserialize {
	public static void main(String[] args) throws Exception {
		
		FileInputStream fis = new FileInputStream("abc.ser");
		ObjectInputStream os = new ObjectInputStream(fis);
		Test t = (Test) os.readObject();
		System.out.println("I value is--" + t.i + ",j value is--" + t.j);
		os.close();
	}
}
				
			

1 thought on “What is serialization and deserialization in java?”

  1. Pingback: What is a transient keyword?

Comments are closed.