Category Archives: IO

Java: Object Externalizable Serialization with Inheritance Example


Serialization in the inheritance with the implementation of Externalizable interface can be done in two ways:

  • Implements Externalizable on the parent class
  • Implements Externalizable on Child class

In these below examples consider both the cases and implementation ways for each.

Pre-requisite:

Example: Serialization in Inheritance where Externalizable interface implements on Parent class Only

Here Externalizable interface implements on parent class and child class also. That’s what override writeExernal() and readExternal() methods on parent and child classes to serialize fields of individual classes.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable{
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCitizenship() {
		return citizenship;
	}

	public void setCitizenship(String citizenship) {
		this.citizenship = citizenship;
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		// own class fields deserialization
		name=(String) in.readObject();
		citizenship=(String) in.readObject();
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		// own class fields serialization
		out.writeObject(name);
		out.writeObject(citizenship);
	}

}

Employee class serializing fields of the self class and calling super.writeExternal() and super.readExternal() to serialize and deserialize fields of the parent class.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee extends Person implements Externalizable {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	/**
	 * Since super class person implemented Externalizable interface then call super.writeExternal() for Serializing the parent class fields.
	 */
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {

		//person superclass fields
		super.writeExternal(out);
		// Employee class fields serilization
		out.writeInt(employeeId);
		out.writeObject(department);
		out.writeInt(salary);
	}

	/**
	 * Since super class person implemented Externalizable interface then call super.readExternal() for Deserializing the parent class fields.
	 * here
	 */
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		// Person superclass fields deserilization
		super.readExternal(in);
		//Employee class fields deserilization
		employeeId = in.readInt();
		department = (String) in.readObject();
		salary =  in.readInt();

	}

}

Here are steps to implements serialization and deserialization of Employee class.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("After Deserilization Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

After executing the above program you will get below result.

Output


Employee Constructor Executed.
Employee object Serialize Successfully
After Deserilization Employee Detail :
Id :111
Name: Saurabh
Department: IT
Salary: 52000
Citizenship: India

Example: Serialization in Inheritance where Externalizable interface implements on Child class Only

Here Externalizable interface implements on parent class and child class also. That’s what override writeExernal() and readExternal() methods on parent and child classes to serialize fields of individual classes.

public class Person {
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}
    //getter and setter of class
}
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee extends Person implements Externalizable {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	//getter and setter of class

	/**
	 * Since super class person not implemented Externalizable interface then for Serializing the parent class fields
	 * we can do it here also.
	 */
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {

		//person superclass fields
		out.writeObject(getName());
		out.writeObject(getCitizenship());

		// Employee class fields serilization
		out.writeInt(employeeId);
		out.writeObject(department);
		out.writeInt(salary);
	}

	/**
	 * Since super class person not implemented Externalizable interface then for deserialize the parent class fields
	 * here
	 */
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		// Person superclass fields deserilization
		setName((String) in.readObject());
		setCitizenship((String) in.readObject());

		//Employee class fields deserilization
		employeeId = in.readInt();
		department = (String) in.readObject();
		salary =  in.readInt();

	}

}

Here are steps to implements serialization and deserialization of Employee class.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("After Deserilization Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

After executing the above program you will get below result.

Output


Employee Constructor Executed.
Employee object Serialize Successfully
After Deserilization Employee Detail :
Id :111
Name: Saurabh
Department: IT
Salary: 52000
Citizenship: India

See Also:

Java: Object Serialization with Inheritance Example


As we have read in the previous post if we implement java.io.Serializable interface on parent class then no need to implement on child class to make it serializable. Here we will discuss for both the cases after java.io.Serializable:

  • Implements Serializable on Parent Class
  • Implements Serializable on Child Class

Pre-requisite:

Example: Serializable interface implements on Parent class Only

Here you will see while the Serializable interface implemented on parent class but all the fields of parent and child class serialized.

import java.io.Serializable;

public class Person implements Serializable{
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCitizenship() {
		return citizenship;
	}

	public void setCitizenship(String citizenship) {
		this.citizenship = citizenship;
	}
}
public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen,int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary=salary;
		System.out.println("Employee Constructor Executed.");
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

Output


Employee Constructor Executed.
Employee object Serialize Successfully
Employee Detail :
Id :111
Name: Saurabh
Department: IT
Salary: 52000
Citizenship: India

Example: Serializable interface implements on Child class Only

Here you will notice parent class fields are not serialize.

public class Person {
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCitizenship() {
		return citizenship;
	}

	public void setCitizenship(String citizenship) {
		this.citizenship = citizenship;
	}
}
import java.io.Serializable;

public class Employee extends Person implements Serializable{
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen,int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary=salary;
		System.out.println("Employee Constructor Executed.");
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

Output


Employee Constructor Executed.
Employee object Serialize Successfully
Employee Detail :
Id :111
Name: null
Department: IT
Salary: 52000
Citizenship: null

See Also:

Java: Serialization Exception Handling


All these exceptions are related to serialization which occurred while doing serialization and deserialization of objects. These exceptions are subclasses of ObjectStreamException which is a subclass of IOException.

Pre-requisite:

Java Serialization exception hierarchy

Exception Description
ObjectStreamException Superclass of all serialization exceptions.
InvalidClassException This exception occurred when  a class cannot be used to restore/deserialize objects for any of these reasons:

  • The class does not match the serialversionUID of the class in the stream.
  • The class contains properties with invalid primitive data types.
  • The Externalizable class doesn’t have a public no-arg constructor.
  • The  Serializable class can’t access the no-arg constructor of its closest non-serializable superclass.
NotSerializableException This exception has thrown by a readObject or writeObject method to terminate serialization or deserialization.
StreamCorruptedException This exception has thrown when some of the meta information modified:

  • If the stream header is invalid.
  • If control information not found.
  • If control information is invalid.
  • JDK 1.1.5 or fewer attempts to call readExternal on a PROTOCOL_VERSION_2 stream.
NotActiveException This exception has thrown if writeObject state is invalid within the following ObjectOutputStream methods:

  • defaultWriteObject
  • putFields
  • writeFields

This exception has thrown if readObject state is invalid within the following ObjectInputStream methods:

  • defaultReadObject
  • readFields
  • registerValidation
InvalidObjectException This exception occured when a restored object cannot be made valid.
OptionalDataException This exception has thrown by readObject when there is primitive data in the stream and an object is expected. The length field of the exception represents the number of bytes that are available in the current block.
WriteAbortedException This exception has thrown when reading a stream terminated by an exception that occurred while the stream was being written.

See Also:

References

Java: static Serialization and Deserialization Examples


The variable declares with static keyword are known as class variables these variables will not serialize when doing serialization for objects of the class.

Note: Fields declare as transient also not serialize.

Pre-requisite:

For Example: In Employee Class fields age is declared with the keyword static. When you serialize the object of class Employee then values of age will not serialize and time of deserialization initialize with default value as per type.

import java.io.Serializable;
public class Employee implements Serializable{
 int id;
 String name;
//This field will not be serialized
 static int age;
 public Employee(int id, String name,int age) {
  this.id = id;
  this.name = name;
  this.age=age;
 }
}

See Also:

Serialization Example: with the static keyword

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

public class SerializationWithStaticExample {

	public static void main(String args[]) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		// writing object into employee file
		FileOutputStream f = new FileOutputStream("employee.txt");
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();

		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

}

Output


Employee object Serialize Successfully

Deserialization Example: with the static keyword

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

public class DeserializationWithStaticExample {

	public static void main(String[] args) throws Exception {
		 //Read object stream from file
		  ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));
		 //Deserialize object stream to employee object
		  Employee e=(Employee)in.readObject();
		  System.out.println("Employee Detail :");
		  System.out.println("Id :"+e.id+"\nName: "+e.name+"\nAge: "+e.age);
		  in.close();  

	}
}

Output


Employee Detail :
Id :111
Name: Saurabh
Age: 0

As you can see, the printing age of the employee returns 0 as default initialize value for int type because the value of age was not serialized.

Java: Externalizable/Custom Serialization and Deserialization Example


The Externalizable interface provides the facility of custom serialization by writing the state of an object into a byte stream by making some changes or compress format.

Pre-requisite:

The Externalizable interface is not a marker interface. It extends Serializable interface and provides two methods for serialization and deserialization of object:
Serialization

public void writeExternal(ObjectOutput out) throws IOException

Deserialization

public void readExternal(ObjectInput in) throws IOException

Advantage of Externalizable

  • Externalizable is fast in comparison to default serialization. Because JVM uses reflection when you use serializable which is quite slow.
  • Externalizable performance is fast because don’t store unnecessary information. While default serialization store information about class description i.e class description, its superclass, and instance variable associated with that class.

Disadvantage of Externalizable

  • Once any change happens on the class definition, we have to also change our implementation on writeExternal() and readExternal() accordingly.
  • In the case of inheritance, the Subclass object has to coordinate with its superclass to save and store its state by calling super.xxxx() method from subclass.

See Also:

Externalizable Example: Serialization and Deserialization

In this example, Employee class override writeExternal() and readExternal() method for serialization and deserialization of data.  Here we have written our own statement to what data need to serialize. Here you can also consider this example of data compression as storing data as compressed because not storing irrelevant data.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee implements Externalizable {
	int id;
	String name;
	transient int age;
	public Employee()
	{

	}
	public Employee(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	@Override
	public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException {
		String []str=oi.readUTF().split("[|]");
		this.id=Integer.parseInt(str[0]);
		this.name=str[1];
		this.age=Integer.parseInt(str[2]);

	}

	@Override
	public void writeExternal(ObjectOutput oo) throws IOException {

		oo.writeUTF(this.id+"|"+this.name+"|"+this.age);
	}

}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ExternalizableCompressionExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		serializeEmployee(e1, "employee.txt");

		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.id + "\nName: " + e1.name + "\nAge: " + e1.age);
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}

}

Output


Employee Detail :
Id :111
Name: Saurabh
Age: 35

Java: transient Serialization Example


Java transient keyword is used in serialization to declare a variable when don’t want to serialize.

Note: Fields declare as static will also not serialize.

Pre-requisite:

For Example: In Employee Class fields age is declared with keyword transient. When you serialize the object of class Employee then values of age will not serialize and time of deserialization initialize with default value as per type.

import java.io.Serializable;
public class Employee implements Serializable{
 int id;
 String name;
//This field will not be serialized
 transient int age;
 public Employee(int id, String name,int age) {
  this.id = id;
  this.name = name;
  this.age=age;
 }
}

See Also:

Serialization Example: with transient keyword

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

public class SerializationWithTransientExample {

	public static void main(String args[]) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		// writing object into employee file
		FileOutputStream f = new FileOutputStream("employee.txt");
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();

		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

}

Output

Employee object Serialize Successfully

Deserialization Example: with transient keyword

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

public class DeserializationWithTransientExample {

	public static void main(String[] args) throws Exception {
		 //Read object stream from file
		  ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));
		 //Deserialize object stream to employee object
		  Employee e=(Employee)in.readObject();
		  System.out.println("Employee Detail :");
		  System.out.println("Id :"+e.id+"\nName: "+e.name+"\nAge: "+e.age);
		  in.close();  

	}
}

Output

Employee Detail :
Id :111
Name: Saurabh
Age: 0

As you can see, the printing age of the employee returns 0 as the default value for int type because the value of age was not serialized.

Java: Serialization and Deserialization Examples


Serialization is a mechanism to convert the state of an object as a byte stream to persist and traverse of an object. Byte stream makes platform independent i.e One object can serialize in a platform and deserialize in another platform.

Reverse operation of serialization is called deserialization i.e convert byte-stream to object.

Advantages of Serialization

  • Use to save/persist state of an object.
  • Use to travel an object across a network i.e also called and marshaling.

Technically, Serialization and deserialization used in Hibernate, RMI, JPA, EJB and JMS technologies to persist the state of the object as a stream.

Java Serialization and Deserialization

In Java, to make an object Serializable implements java.io.Serializable interface which is a marker interface (has no data member and methods).

See Also:

Object Serialization

We can call writeObject() method of ObjectOutputStream class for serialization of object.

public final void writeObject(Object obj) throws IOException

Object Deserilization

We can call readObject() method of ObjectInputStream class for deserialization of object.

public final Object readObject() throws IOException, ClassNotFoundException

Points to remember

  • The objects of those classes will able to serialize which are implementation java.io.Serializable interface.
  • If the parent class implemented a Serializable interface then the child class doesn’t need to implement it but vice-versa is not true.
  • Internal associated component objects of a class must implement the Serializable interface.
  • Object Constructor never called when an object is deserialized.
  • Static and transient data members of the class are not serialized. If you don’t want to serialize some of the data members make it transient.
  • In the case of array or collection, all the objects of array or collection must be serializable. If any object is not serializable, serialization will be failed.

For Example :

//Implemneted Serilizable interface to make objects of
//ClassA serializable eligible
class ClassA implements Serializable{
//Associate component object Class also need to
//implement Serializable
ClassB ob=new ClassB();
}

What is SerialVersionUID?

On-time of Serialization on an object of Serializable class associate a version called as SerialVersionUID. This version is used during Deserialization to verify that the sender and receiver of a serialized object loaded classes are compatible with respect to serialization.

In case receiver loaded class have different version UID than sender’s class then it will throw an exception as InvalidClassException.

We can explicitly declare SerialVersionUID as long in Serializable class as below:

private static final long serialVersionUID=26L;

Note: Use access modifier as private because this field is not useful for inherited classes.

Recommendation: Always explicitly declare SerialVersionUID for serializable classes with some long value because if not mentioned explicitly then compute at runtime i.e highly sensitive to class details that may vary depending on compiler implementations or any change in class fields etc. which can generate different SerialVersionUID. This different SerialVersionUID may affect the time of the deserialization of the object.

serialver

To manually check serialVersionUID of java classes. JDK provided a tool serialver. We can run this tool as below:

serialver [-classpath classpath] [-show] [classname…]

Example: Serialization and Deserialization

This Employee object needs to serialize and deserialize in the given example. The employee object implements java.io.Serializable marker interface that is required to mark as an object is eligible for serialization.

import java.io.Serializable;

public class Employee implements Serializable {
	int id;
	String name;
	int age;

	public Employee(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
}

Here we have written a separate method for the implementation of serialization and deserialization.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserilizationExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.id + "\nName: " + e1.name + "\nAge: " + e1.age);
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}

}

Output

Employee object Serialize Successfully
Employee Detail :
Id :111
Name: Saurabh
Age: 35

Java: System.out Vs System.in Vs System.err classes and methods.


The java.lang.System class, having three static members (in, out and err) that pre-initialize at JVM startup that’s what no need to initialize. These classes also known as Stream classes.

Out of these System.out is most frequent use by programmers to write output on the console.

System Stream Classes

Here is a list of System Stream classes objects:

  • System.in
  • System.out
  • System.err

System.in

System.in is an InputStream type object which is typically connected to the keyboard input of console programs.

Note: It’s generally used often, Mainly used by beginner-level programmers to insert input from the keyboard. Because when you consider for application-level data is commonly passed to program by:

  • Command-line arguments
  • Configuration files
  • Application GUI

See Also:

System.out

System.out is a PrintStream type used to outputs the data to the console.

Note: It’s the most frequent used Stream object to print out of the program and for debugging about the flow and values.

System.err

System.err is a PrintStream type mainly used to output an error texts to console.

Note: Some of IDE like eclipse show System.err output in the console in red color so that you can easily see error messages.

Example for System .in, System.out and System.err

In this example, you will see, How to insert value to a program by the keyboard by System.in. Output to console by System.out and for any error print by System.err.

System in out and Err Example
Example System.in, System.out and System.err

Output

System in out err result

Exchanging System Streams

By default System Stream class is to console, but we can also change System Streams by programmatical configuration for each type so that InputStream for System.in or OutputStream for System.out or System.err will read and write to the new stream.

  • System.setIn() : This method use to change input stream.
  • System.setOut() : This method use to change output stream.
  • System.setErr() : This method use to change error output stream.

See Also:

System.out Stream Change

In the below example, out will be got to the given file instead of default OutputStream as Console.

OutputStream output = new FileOutputStream("c:\\output\\FacingIssuesOnIT_logs.txt");
PrintStream printOut = new PrintStream(output);

//This method will change output stream.
System.setOut(printOut);