Booleans are the standard procedure for marking object properties as NULL .
Consider this case:
public class LongMessage implements Writable { private long tag; private String data;
So data may be NULL for some reason. Therefore, I would do the read / write as follows:
@Override public void readFields(DataInput in) throws IOException { tag = in.readLong(); if (in.readBoolean()) { data = in.readUTF(); } else { data = null; } } @Override public void write(DataOutput out) throws IOException { out.writeLong(tag); if (data != null) { out.writeBoolean(true); out.writeUTF(data); } else { out.writeBoolean(false); } }
It is even pretty readable. But keep in mind that you have a fixed overhead of one byte per write, as stated in JavaDocs #writeBoolean :
Writes a boolean value to this output stream. If v is true, the value (byte) 1 is written; if v is false, the value (byte) 0 is written
source share