O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading and Writing Booleans

The DataOutputStream class has a writeBoolean() method and the DataInputStream class has a corresponding readBoolean() method:

public final void writeBoolean(boolean b) throws IOException
public final boolean readBoolean() throws IOException

Although theoretically a single bit could be used to indicate the value of a boolean, in practice a whole byte is used. This makes alignment much simpler and doesn’t waste enough space to be an issue on modern machines. The writeBoolean() method writes a zero byte (0x00) to indicate false, a one byte (0x01) to indicate true. The readBoolean() method interprets as false and any positive number as true. Negative numbers indicate end of stream and lead to an EOFException being thrown.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required