How to Serialize Deserialize List of Objects in Java? Java Serialization Example

Serialize - DeSerialize an Object

Java provides a mechanism, called object serialization 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.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Another must read:

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

Here is a complete example. These are the steps:

  1. Create Class Item() which implements Serializable.
  2. In Main – Create 2 Item Objects.
  3. Add it to ArrayList.
  4. Serialize the ArrayList. Checkout file to see bytestream of an Object. (Below image)
  5. Deserialize the bytestream from the same file to see Object.

Serialize File Content

Output:

List of all Java Tutorials and Spring MVC Tutorials which you might be interested in.

Have anything to add to this article? Please chime in and join the conversion.

Enjoyed this post?

Be sure to subscribe to the Crunchify newsletter and get regular updates about awesome posts just like this one and more! Join more than 13000 subscribers!

  • John DeRegnaucourt

    Check out json-io for JSON serialization (bi-directional) of Java objects. It’s faster than the JDK’s ObjectInputStream and ObjectOutputStream, and it’s format is human readable JSON. Json-io does not require your objects to implement ‘Serializable’. This is a major limitation to the JDK’s serialization because it limits it’s usefulness when you do not control the code for all the classes of objects you wish to serialize.

    • http://crunchify.com/ App Shah

      Thanks for suggestion John.

  • Rick S

    The package name has to be the exact same when in a different JVM.