Java Serialization

In Java, serialization is a mechanism where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object

Java Serialization Example

Here is an example program, demonstrates serialization in Java:

/* Java Program Example - Java Serialization */
      
import java.io.*;

public class JavaSerialization
{
   public static void main(String [] args)
   {
      Student stob = new Student();
      stob.name = "Deepak Patel";
      stob.address = "Varanasi, India";
      stob.SSN = 11122333;
      stob.number = 101;
      
      try
      {
         FileOutputStream fileOut = new FileOutputStream("/tmp/student.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(stob);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/student.ser");
      }
      catch(IOException i)
      {
         i.printStackTrace();
      }  
   }
}

Here is an example program, deserializes the the Student object created as in above Java program:

/* Java Program Example - Java Serialization */

import java.io.*;

public class JavaDeserialization
{
   public static void main(String [] args)
   {
      Student sdob = null;
     
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/student.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);   
         sdob = (Student) in.readObject();
         in.close();
         fileIn.close(); 
      }
      catch(IOException i)
      {
         i.printStackTrace();
         return;
      }
      catch(ClassNotFoundException c)
      {
         System.out.println("Student class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Student...");
      System.out.println("Name = " + sdob.name);
      System.out.println("Address = " + sdob.address);
      System.out.println("SSN = " + sdob.SSN);
      System.out.println("Number = " + sdob.number);  
   }
}

Here is the output of the above Java program:

Deserialized Student...
Name = Deepak Patel
Address = Varanasi, India
SSN = 0
Number = 101

Java Online Test


« Previous Tutorial Next Tutorial »