Hello ranchers,
I was trying to find the size of an object in
Java , but the outputs are surprising.
Here is the code
---------------------------------------------------------------------------
class A
{
}
class Size
{
public static void main(
String arg[])
{
Runtime r = Runtime.getRuntime();
long mem1=0 , mem2 =0 ;
System.out.println("Total Memory = " + r.totalMemory());
r.gc();
mem1=r.freeMemory();
System.out.println("Memory before Allocation = " + mem1);
//byte by[] = new byte[1000];
//int in[] = new int[1000];
//byte bc[] = new byte[4];
//byte bc[] = new byte[5];
//A z = new A(); // 72
r.gc();
mem2=r.freeMemory();
System.out.println("Memory after Allocation = " + mem2);
System.out.println("Memory Used = " + (mem1-mem2));
}
}
---------------------------------------------------------------------------
if i uncomment
//byte by[] = new byte[1000];
it gives me output 1016 (i think it is alloacting 1 byte for each byte variable and 16 byte is the size of reference of reference variable)
Similarly
//int in[] = new int[1000];
it gives me output 4016
But when i do
//byte bc[] = new byte[4];(Output 16)
//byte bc[] = new byte[5];(Output 24)
I can not understand , when i give the size of the array 5 it gives output as 24 but when size is 4 or less it gives 16.
(at least on my machine)
and if i instantiate z only and comment all above instantiation i get
A z = new A(); output as 72 .
Why am i getting output like this

Please explain
Thanks in advance
[ February 18, 2006: Message edited by: faisal usmani ]