Serialization is the process of converting Java objects into a stream of bytes. The stream of bytes can be transmitted through a network connection, stored in a database as a BLOB object or saved as a binary file. The stored or transmitted stream of bytes can be reconstructed to Java object later. This article explains Serialization in Java, using a simple step by step example.
Create a Student class with the attributes name, and age.Note: The sample codes provided in this tutorial, use try-with-resources blocks to auto close the input and output streams. You need Java 7 or latest version to compile and run these codes. For more information about try-with-resources, visit to this tutorial: Try With Resources
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}Create a Main class as shown below, to create an object of Student.public class Main {
public static void main(String[] args) {
Student stu = createStudent();
System.out.println("Name: " + stu.getName());
System.out.println("Age: " + stu.getAge());
}
/**
* Create a sample Student object.
*
* @return a Student object.
*/
public static Student createStudent() {
// Create a Student object
Student stu = new Student();
stu.setName("Alice");
stu.setAge(24);
return stu;
}
}

