Writing Primitive Types and Objects Efficiently
What You'll Learn
You'll learn how to use DataOutput methods in writeExternal to write primitives and objects in a compact, efficient binary format.
The Core Idea
When implementing Externalizable, your writeExternal method receives an ObjectOutput parameter, which extends DataOutput. This interface provides specialized methods for writing Java primitives and objects directly in binary form—far more efficient than converting everything to strings or relying on default serialization overhead.
The key methods you should master:
writeInt(int v)– Writes a 32-bit integer (4 bytes)writeLong(long v)– Writes a 64-bit long (8 bytes)writeUTF(String s)– Writes a string in modified UTF-8 (compact, variable-length)writeObject(Object obj)– Serializes an object reference
These methods let you control exactly how your data is written—byte by byte—giving you maximum efficiency and minimal file size.
Think of It Like Packing a Suitcase
Default serialization is like throwing items in randomly with lots of bubble wrap. Using DataOutput methods is like vacuum-packing each item precisely: you know exactly what space each takes, and you waste nothing.
Example Pattern
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(userId); // Exactly 4 bytes
out.writeLong(timestamp); // Exactly 8 bytes
out.writeUTF(username); // Variable, but compact
out.writeObject(metadata); // Another serializable object
}
Notice the order matters! Your readExternal must read data in the exact same sequence and types.
Why This Matters
Using the right method for each type dramatically reduces serialized size and improves I/O performance. An int takes exactly 4 bytes with writeInt, whereas default mechanisms add metadata overhead.
Key Takeaway: Master writeInt, writeLong, writeUTF, and writeObject in your writeExternal implementation to achieve compact, efficient serialization with full control over the binary format.