Monday, 26 September 2016

Java Tutorial : Java IO (Java ObjectOutputStream | Java Serialization)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction to ObjectOutputStream

In Java, serialization is the process of converting an object's state into a binary stream of bytes so it can be saved to a file, persisted into a database, or transmitted across a network. The fundamental class that makes this possible is ObjectOutputStream from the java.io package.

How ObjectOutputStream Works

ObjectOutputStream is a processing stream that wraps around an existing low-level byte output stream, such as a FileOutputStream. It implements both the ObjectOutput and DataOutput interfaces, allowing it to write full Java objects as well as raw primitive data types directly into the byte stream.

Core Methods of ObjectOutputStream

  • writeObject(Object obj): The primary method used to serialize an object. It writes the class descriptor, class signature, and the non-transient, non-static field values into the destination stream.
  • Writing Primitive Types: Provides dedicated methods inherited from DataOutput like writeInt(int val), writeDouble(double val), writeBoolean(boolean val), and writeUTF(String str).
  • flush() and close(): Flushes buffered output bytes and releases underlying OS resources.

Important Serialization Rules

1. Must Implement Serializable: Any object passed into writeObject() must implement either java.io.Serializable or java.io.Externalizable. If it does not, the JVM throws a runtime NotSerializableException.

2. Static and Transient Fields: By default, ObjectOutputStream skips any field marked with transient or static, ensuring only instance state is persisted.

3. Handling Object Graphs: If the serialized object contains references to other objects, ObjectOutputStream serializes the complete graph of reachable objects automatically.

Related Tutorials from Ram N Java

No comments:

Post a Comment

Tutorials