🚀 Enjoying Java Tutorials?
Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!
🔔 Subscribe to Ram N JavaIntroduction 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
DataOutputlikewriteInt(int val),writeDouble(double val),writeBoolean(boolean val), andwriteUTF(String str). -
flush()andclose(): 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.
No comments:
Post a Comment