Menu
Topics Index
...
`

Serializable Test - Java Example Program


Serializable Test
import java.io.*;

class SerializableTest
{
    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
    
        // SERIALIZATION - START
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        Student hemanth = new Student();
        hemanth.name = "Hemanth";
        hemanth.rollNumber = 25;
        hemanth.section = 'C';
        System.out.println("Before - " + hemanth.name + " " + hemanth.rollNumber + " " + hemanth.section);
        oos.writeObject(hemanth); // LINE A
        oos.close();
        byte[] objectDataBytes = baos.toByteArray();
        // SERIALIZATION - END
    
        // DESERIALIZATION - START
        ByteArrayInputStream bais = new ByteArrayInputStream(objectDataBytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Student hemanthRestored = (Student) ois.readObject(); // LINE B
        System.out.println("After - " + hemanthRestored.name + " " + hemanthRestored.rollNumber + " " + hemanthRestored.section);
        ois.close();
        // DESERIALIZATION - END
    }

}

class Student implements Serializable
{

    String name = "";
    int rollNumber = 0;
    char section = 'A'; // LINE C
}
OUTPUT

Before - Hemanth 25 C
After - Hemanth 25 C

DESCRIPTION

Here we are creating an ObjectOutputStream using an ByteArrayOutputStream. Then we are serializing the created hemanth object into the ObjectOutputStream at LINE A. By doing this the object data, basically "Hemanth", 25 and C are converted into bytes and then written into the output stream.
Later the converted bytes data is given as input to ByteArrayInputStream which in-turn is input to ObjectInputStream. At LINE B, using the ObjectInputStream the object data is read back or de-serialized. Since we know the read object is Student, we are type casting it to that class.
As you can see the data before serialization and the after serialization is same and both times it prints Hemanth 25 C.

THINGS TO TRY
  • Add one more variable percentage of type double to the Student class and initialize it 75.6. Change before and after println statements and see that the value 75.6 is retained even after the de-serialization process.
  • Make the section variable as transient, by adding the transient keyword before char at LINE C. See that the section will be changed to the default value of 'A'. As you know, transient variables will not be serialized.

© meritcampus 2019

All Rights Reserved.

Open In App