Why does the boolean data type need 8 bits?

java

Solution

I think it may need more than 8 bits. It depends on JMV." In Oracle JVM primitive `boolean` needs 8 bits, the reason is limited support and lack of optimization.

Read also: What is the size of a boolean variable in Java?

After The Java Tutorials - Primitive Data Types

boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

After The Java® Virtual Machine Specification

Although the Java Virtual Machine defines a boolean type, it only provides very limited support for it. 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.

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.

For example Boolean type looks in memory like this

header:   8 bytes 
value:    1 byte 
padding:  7 bytes
------------------
sum:      16 bytes

As an alternative to `boolean[]` you can use for example java.util.BitSet.

Why is hard to store booleans as 1 bit? Read Vlad from Moscow answer. You cant address one bit of memory.

Problem

Boolean data type only evaluates to `true` or `false`, so it is always going to take only one bit of memory. So why is there a need of extra 7 bit of memory, isn't it a waste of memory?

Original source

Related problems