I would like to know exactly the real space allocated in memory for an object.
I try to explain with some example: using a 64 bit JVM, pointer size should be 8 bytes, so:
Object singletest = new Object();
will take 8 bytes to reference the Object plus the size of the ObjectObject arraytest = new Object[10];
will take 8 byte to reference the position where the array is stored plus 8*10 bytes to store the array plus the size of each Objectint singleint = new int;
will take just 2 bytes, because int is a primitive typeint[] arrayint = new int[10];
will take 8 bytes to reference the position and 10*2 bytes for the elements
Moreover, this is the reason why Java allows to write code like this:
int[][] doublearray = new int[2][];
int[0][] = new int[5];
int[1][] = new int[10];
What really happen is that an array will produce a reference (aka pointer) like an object, so it doesn't really matter the size of the second dimension at declaration time (and dimensions can be different, there is no link between them). Then the space taken will be: a reference to doublearray (8 bytes), first dimension is simply a reference to the second one, so other 8 bytes * 2 (first dimension size), and finally 2 bytes * 5 plus 2 bytes * 10.
So, finally, if have a real class like this:
class Test {
int a, b;
int getA() {return A};
void setA(int a) {this.a = a;}
int getB() {return B};
void setB(int b) {this.b = b;}
}
when I call a new to instantiate, a pointer (or name it reference, because it's Java) of 8 bytes will be used plus 2+2bytes to store the integers into the class.
The questions are: am I right or I wrote total nonsense? Moreover, when I don't instantiate an object but I just declare it, 8 bytes will be allocated for further use or not? And what if I assign a null value?
Meanwhile for primitive type I'm quite sure that just declaring it will allocate the requested space (if I declare an "int i" then I can immediately call i++ because no reference are used, just a portion of memory is setted on "0").
I searched on internet without clever response... I know that I wrote a lot of questions, but any help will be appreciated! (and maybe I'm not the only one interested)