Java – Why is Boolean Size Not Defined?

booleanconceptsjava

I see size of boolean is not defined. Below are two statements I see at java primitive data size

not precisely defined

Further explanation says

boolean represents one bit of information, but its "size" isn't
something that's precisely defined.

Question came to my mind was why boolean in java can't be represented with 1 bit(or 1 byte if byte is minimum representation ) ?

But I see it has been already answered at https://stackoverflow.com/questions/1907318/why-is-javas-boolean-primitive-size-not-defined where
it says

the JVM uses a 32-bit stack cell, used to hold local variables, method
arguments, and expression values. Primitives that are smaller than 1
cell are padded out, primitives larger than 32 bits (long and double)
take 2 cells

Does it mean even byte/char/short primitiva data types also take 32 bit though their size is defined as 8/16/16 bit ?

Also can we say boolean size will be 32 bit on 32 bit cpu and 64 bit on 64 bit cpu ?

Best Answer

TL;DR The only thing that's sure is that boolean occupies at least one bit. Everything else depends on the JVM implementation.

The Java Language Specification doesn't define sizes, only value ranges (see The Language Spec). So, it's not only the boolean size that's undefined at this level. And boolean has two possible values: false and true.

The Virtual Machine Specification tells us that boolean variables are treated like int with values 0 and 1. Only arrays of boolean have specific support. So at the Virtual Machine level, a boolean variable occupies the same amount of space as an int, meaning one stack cell: at least 4 bytes, typically 4 bytes on 32-bit Java and 8 bytes on 64-bit.

Finally there's the HotSpot engine that compiles JVM bytecode into optimized CPU-specific machine code, and I bet that in many cases it's able to deduce the limited value-range of an int-masked boolean from the context and use a smaller size.