简体   繁体   中英

Boolean range in Java programming language

I found the below paragraph in SCJP 6.0 book. What does it mean by the last statement.Which book to read about how these variables are actually stored in memory?. Thanks a lot.

"That's virtual-machine dependent."

For boolean types there is not a range; a boolean can be only true or false. If someone asks you for the bit depth of a boolean, look them straight in the eye and say, "That's virtual-machine dependent." They'll be impressed.

It means that the only thing required from boolean is to be true or false , no matter what is the underlying implementation.

JLS states:

The boolean type has exactly two values: true and false.

Where for integral types:

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.

So you have required bit depth for integral types but it is solely up to you if your boolean will be represented in the memory as a single bit, byte or multibyte variable when you implement your own JVM.

What is being said is that a VM can implement a boolean as an integer, where a positive value is true and 0 or a negative value is false. The idea is that as long as the VM handles booleans strictly as true or false, it doesn't matter how the VM implements booleans at the OS level.

It's entirely virtual machine dependent because they're expecting you to use boolean s sparingly. Sure you're going to use them all the time, but you're highly unlikely to have more than a handful in a given class.

You are most definiately not going to have something like boolean[] - they made java.util.BitSet for that purpose. It just makes more sense to leave boolean s being whatever size they want (8, 16, 32 bits) and keeping it simple than the alternative, which would essentially be a BitSet internally keeping track of all the booleans. That would've been a poor design decision, imo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM