Discovery
Whenever I find something interesting, I write it here.
Size of boolean
in Java
I always assume the boolean
data type takes only 1 bit of space in memory, but I’m wrong when I search it on Google. A similar question from StackOverflow says:
It’s virtual machine dependent.
And it seems that in Sum’s JVM, it uses 1 byte for boolean array and it may uses no less than 1 byte for individual boolean. The reason for that must be the trade off for speed since the memory addressing is “usually” 1 byte long.
Also, worth noting from this link that all primitive wrapper classes except Boolean have a BYTES constant, which gives data type’s size in bytes:
Size of byte: 1 bytes.
Size of short: 2 bytes.
Size of int: 4 bytes.
Size of long: 8 bytes.
Size of char: 2 bytes.
Size of float: 4 bytes.
Size of double: 8 bytes.
When you really in a space constrain environment, the java.util.BitSet
is the way to go since it use 1 bit for each flag but may be slower. More details here.
The i & (-i)
Assume a number n, we can write the binary representation of n
as A1B
, A is the number before the least significant 1
and B
as the zeros after that. For example: number 6 is 110
write as A1B where A = 1 (the most left one, with all the zeros not shown)
and B = 0 (most right)
.
For -n
, if we want to represent it use A1B
notation, then:-n
= flip the bits of A1B + 1
= ~A0~B
where ~B
consist of all ones, for example: for number -6, flip of A
= 111…10, B
= 1. When we do + 1
, the bits in ~B
flip back to 0 and flips the middle bit to 1 again:
-num = (a1b)¯ + 1 = a¯0b¯ + 1 = a¯0(0…0)¯ + 1 = a¯0(1…1) + 1 = a¯1(0…0) = a¯1b.