Java Serialization of Data Types

Java Serialization of Data Types


We know earlier in "What is Serialization?", to write an object to a file, the object must be serialized. For this reason, the Student class was serialized in "Java Serialization Example" and then Student objects are written to a file. It is all okay, but if would like to write a string to a file or a Date object to a file or a Vector object to a file, then who will serialize them; they are all predefined classes bundled with Java API packages.

To overcome this difficulty, the Java designers already Serialized many classes and supplied to us so that the programmer can write them to a file or send across network. Let us see some class signatures of Java API classes.

  1. public final class java.lang.String implements java.io.Serializable, java.lang.Comparable, java.lang.CharSequence
  2. public class java.util.Date implements java.io.Serializable, java.lang.Cloneable, java.lang.Comparable
  3. public class java.util.Vector extends java.util.AbstractList implements java.util.List, java.util.RandomAccess, java.lang.Cloneable, java.io.Serializable

Let us write an application on serialization where Java API class objects(like String, Date, Integer etc.) and some primitive data types (like int, long etc.) are written to a file and then read back. Two programs exist.

  1. UsingWriteMethods.java : Writes to a file the object like Vector, Date, String, Integer and data types like int, double, long etc.
  2. UsingReadMethods.java : Reads from the file, all the data written by UsingWriteMethods.java

1st Program File Name: UsingWriteMethods.java

2nd Program File Name: UsingReadMethods.java

The writing and reading methods of object streams are shown in Java API classes supporting Serialization.

Learn the variations of getMessage() & printStackTrace().

One thought on “Java Serialization of Data Types

  1. Rajeswari K

    Hi Sir,

    In the above implicit serialization example,when youread the integer,vector objects using ois.readObject(),we have not specified the order.That is,the first readObject() myt retrieve the Integer object stored rather than the Date object.So how can we ensure the order?
    Or is the retrieval order should be same as storage?

Leave a Reply

Your email address will not be published. Required fields are marked *