Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit pattern(variable value) for boolean in java?

Tags:

java

as we know in java variables are bit holders with a designated type. And for primitives the bits represents a numeric value.

For example. a byte with value 6 has a bit pattern 00000110.

so i wanted to know as boolean is also a primitive what is the bit pattern for it for value true and false.

like image 621
GuruKulki Avatar asked Jan 17 '10 17:01

GuruKulki


3 Answers

Internally in the bytecode/VM booleans are represented as bytes with the bit patterns 00000001 for true and 00000000 for false. But that information doesn't buy you anything as a Java developer as you simply can't access or otherwise use the numerical represantation of booleans in Java as Java has them strictly seperated from numbers.

Edit: I just looked up the Java VM Spec again and found out my answer was wrong. Contrary to what I said before, booleans are stored as CONSTANT_Integer structs in byte code which makes them occupy 4 bytes for data in the constant pool, but as the constant pool is unified, there can be at most 2 boolean entries in any class. And since a reference to the constant pool is always 2 bytes wide, a array of booleans would occupy 2 bytes per entry in the byte code.

like image 129
x4u Avatar answered Oct 19 '22 09:10

x4u


Yes, as skaffman said: True is 1 and false is 0.

But that doesn't really matter, because unless you look at serialized data outside your program, you're unlikely to ever see those values in the wild.

For what it's worth, common Java implementations actually store booleans in integer-sized fields, i.e. they have 31 zero's worth of padding around that single bit of information. Accessing 32 bits at a time is a little bit faster than grabbing one byte from among 4, and much faster than digging a single bit out of a byte. This optimization makes arrays of booleans annoyingly large, though. If you have many, many bits to deal with and need to cut down on space, you're better off using BitSet.

like image 39
Carl Smotricz Avatar answered Oct 19 '22 07:10

Carl Smotricz


If I am not wrong JVM specification does not mandate how the boolean values have to be represented internally. How the value is represented internally is vendor specific and does not matter to the programmer as this detail is totally transparent to programs running over the JVM.

like image 25
Aadith Ramia Avatar answered Oct 19 '22 07:10

Aadith Ramia