Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program to calculate the size of a boolean variable [duplicate]

Possible Duplicate:
Java - boolean primitive type - size

I've designed this program to calculate the size of a boolean in Java.

public class BooleanSizeTest{
    /**
     * This method attempts to calculate the size of a boolean.
     */
    public static void main(String[] args){
        System.gc();//Request garbage collection so that any arbitrary objects are removed.
        long a1, a2, a3;//The variables to hold the free memory at different times.
        Runtime r = Runtime.getRuntime();//Get the runtime.
        System.gc();//Request garbage collection so that any arbitrary objects are removed.
        a1 = r.freeMemory();//The initial amount of free memory in bytes.
        boolean[] lotsOfBools = new boolean[10_000_000];//Declare a boolean array.
        a2 = r.freeMemory();
        System.gc();//Request garbage collection.
        a3 = r.freeMemory();// Amount of free memory after creating 10,000,000 booleans.
        System.out.println("a1 = "+a1+", a2 = "+a2+", a3 = "+a3);
        double bSize = (double)(a1-a2)/10_000_000;/*Calculate the size of a boolean 
        using the difference of a1 and a2*/  
        System.out.println("boolean = "+bSize);
    }
}

When I run the program, it says that the size is 1.0000016 bytes. Now, the Oracle Java documentation says that the size of a boolean is "not defined". [See link]. Why is this so? Also, a boolean variable represents 1 bit of information (true and false), so what happens to the remaining seven bits?

like image 879
JavaNewbie_M107 Avatar asked Oct 06 '22 11:10

JavaNewbie_M107


1 Answers

Accessing 1 bit is an expensive operation; if you retrieve data from memory, you are most likely to do it by word, or by byte. In Java, the internal representation of a boolean is an implementation detail that you shouldn't be concerned unless you are doing a VM implementation.

like image 116
Luis Avatar answered Oct 10 '22 03:10

Luis