Serialization and Deserialization

Overview

  • Serialization is a mechanism of converting the state of an object into a byte stream. ​
  • Deserialization is the reverse process where the byte stream is used to recreate theactual Java object in memory. ​
  • This mechanism is used to persist the object.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationExample {

	public static void main(String[] args) {
		// create User object
		User user = new User(101, "John", "Peter", "Smith", "IT");
		System.out.println(user);
		
		System.out.println("before serialization...");
		// serialization - write to file
		try (ObjectOutputStream writer = 
				new ObjectOutputStream(new FileOutputStream("user.out"))){
			
			writer.writeObject(user);
			
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		
		System.out.println("before deserialization...");
		// deserialization - reading from file
		try (ObjectInputStream reader = 
				new ObjectInputStream(new FileInputStream("user.out"))) {
			
			// read the object user
			User u = (User) reader.readObject();
			System.out.println(u);
			
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	} 

}

Advantages of Serialization

  • To save/persist state of an object. ​
  • To travel an object across a network.

The transient Keyword

  • transient is a variables modifier used in serialization. ​
  • At the time of serialization, if we don’t want to save value of a particular variable in a file,then we use transient keyword. ​
  • When JVM comes across transient keyword, it ignores original value of the variable andsave default value of that variable data type.
  • transient keyword plays an important role to meet security constraints. ​
  • There are various real-life examples where we don’t want to save private data in file. ​
  • Another use of transient keyword is not to serialize the variable whose value can becalculated/derived using other serialized objects or system such as age of a person,current date, etc.