🚀 Enjoying Java Tutorials?
Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!
🔔 Subscribe to Ram N JavaIntroduction
While Java serialization is widely recognized for saving objects, you frequently need to write and restore raw primitive values—such as int, boolean, double, or long—directly to an output stream. In this guide, we break down how Java IO handles primitive serialization using ObjectOutputStream and ObjectInputStream.
Writing and Reading Primitive Data
ObjectOutputStream implements the DataOutput interface, providing dedicated methods to write primitive values directly into the byte stream without wrapping them in complex custom objects.
Common Methods for Writing Primitives
writeInt(int val): Writes a 32-bit integer.writeDouble(double val): Writes a 64-bit double-precision floating point number.writeBoolean(boolean val): Writes a boolean value as a 1-byte value.writeUTF(String str): Writes a string using modified UTF-8 encoding.
Restoring Primitives with ObjectInputStream
To read the primitives back, ObjectInputStream implements DataInput and provides matching methods:
readInt()readDouble()readBoolean()readUTF()
Key Rules to Remember
Order Matters: Primitive values must be read back in the exact same sequence and type order in which they were written. Reading an int when a double was written will result in corrupted data or stream errors.
Mixing Objects and Primitives: You can seamlessly combine calls to writeObject() and primitive write methods like writeInt() on the same stream, provided you mirror the operations during deserialization.
Related Tutorials from Ram N Java
Click here to watch in Youtube :
https://www.youtube.com/watch?v=hupxVOkTnhM&list=UUhwKlOVR041tngjerWxVccw
