Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the boolean data type need 8 bits? [duplicate]

Tags:

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?

like image 248
imGs Avatar asked Jan 06 '14 10:01

imGs


2 Answers

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.

like image 128
MariuszS Avatar answered Sep 29 '22 02:09

MariuszS


It depends of addressability of the memory. The least addressable unit is byte. You can take an address of a byte and do the address arithmetic with it. Moreover there are built-in machine commands that operate with bytes. However it is impossible to take the address of a bit and perform the address arithmetic. In any case at first you have to calculate the address of the byte that contains the target bit and apply additional machine commands that depend of the position of the bit in the byte that to set or reset this bit.

like image 34
Vlad from Moscow Avatar answered Sep 29 '22 02:09

Vlad from Moscow