Two Things Every Java Developer Should Know About Booleans

adminguy's picture
Posted April 3rd, 2015 by adminguy


We are going to re-examine some really basic concepts in this article. In the first section, we will look at a common performance pitfall in instantiating Boolean objects and how to avoid it; and in the second section we will examine a common fallacy of how much space a boolean value occupies in the JVM.
Avoid instantiating a Boolean object

Have you instantiated a Boolean object like this?

Boolean b = new Boolean( false);
Code Example 1

It's a simple line of code which creates a Boolean object. Nothing obviously wrong with it, but look and think a bit harder; what if your software created a million Boolean objects? Wouldn't that be a waste? After all there are only two Boolean values: true and false, so why not just create two constants and use them a million times? That'll certainly save all the cycles required to create so many redundant objects. 

To make our lives even easier, the Boolean class gives us these two constants out of the box: Boolean.TRUE, and Boolean.FALSE. Instead of creating objects, just use these constants as shown in Code Example 2 and make your program a little bit better and faster.

Boolean b = Boolean.FALSE;

Code Example 2
Don't Expect a primitive Boolean value to occupy only 1 bit
It's logical to think that a boolean primitive value will take 1 bit of memory, and unfortunately it's a fallacy that many Java developers have bought into. Boolean values in Java almost always take more than a bit - significantly more.
There are no Java virtual machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data type. -- The Java Virtual Machine Specification
What this means is boolean values always take more than one byte, but how much more depends where the value is being stored: in the stack, or on the heap. 
The JVM uses a 32-bit stack cell, which will cause each boolean value to occupy an entire stack cell of 32 bits. However, the size of boolean values on the heap are implementation dependent. The semantics of storing objects and data on the heap falls under the 'private implementation' rules of the JVM. This means the JVM implementation can choose the size of boolean values on the heap.
Boolean arrays, however, are encoded as arrays of bytes, giving 8 bits to every boolean element of the array:
In Oracle’s Java Virtual Machine implementation, boolean arrays in the Java programming language are encoded as Java Virtual Machine byte arrays, using 8 bits per boolean element.
And finally, according to this answer on SO, Boolean object take 16 bits of memory:
header:   8 bytes 
value:    1 byte 
padding:  7 bytes
sum:      16 bytes