I want to study Java again, because I leave it some years ago. Reading a book I had a problem understanding how Java allocate memory in heap and in stack.
This is what I’ve understood – I’ll try to speak about it with examples.
class TestA {
int a;
void methodA(int b) {
a = b;
}
int getA() {
return a;
}
}
This is a sample class to show different situation. And this is my main:
int b = 3;
TestA obj = new TestA();
obj.methodA(b);
obj.getA();
So what happen?
## BEGIN
STACK – take some memory for main function
HEAP – empty
## int b = 3
STACK – [take some memory for main function -> here we have b]
HEAP – [empty]
## TestA obj = new TestA()
STACK – [take some memory for main function -> here we have b and a reference to TestA]
HEAP – [take some memory for int a]
## obj.methodA(b);
STACK – [take some memory for main function -> here we have b and a reference to TestA]
HEAP – [take some memory for int a] AND [another memory for methodA]
## execute methodA(int b)
STACK – [take some memory for main function -> here we have b and a reference to TestA] AND [take memory for methodA() -> here we have b used in this function]
HEAP – [take some memory for int a] AND [another memory for methodA]
We have:
- object AND instance field (primitive or not) in the heap
- function and scope value in stack
Is it right?
At the outset, remember that the heap will also have the
Classinstance for your class (and several others).Re:
awill be in the heap, not on the stack, as part of the memory allocated for the instance ofTestA.bandobjare on the stack, allocated upon entry tomain(er, I think that’s when that happens; it could be that the JVM doesn’t reserve stack space for them until it encounters the declarations in the program flow, but there we’re getting into internals of the JVM). The heap also contains the instance ofTestA. (Remember thatobj, the variable, is quite distinct from what it points to [the instance ofTestA]; each of those things takes memory.)Also remember that the stack will contain the return addresses for the function calls. E.g., when
maincallsmethodA, the address that the JVM should come back to whenmethodAreturns is also on the stack.Various stack structures will also be allocated for exception handling.
The above is mostly theoretical, mind. JVMs are welcome to do optimizations, and they do (HotSpot is a thoroughly optimizing JVM). @Voo points out, for instance, that JVMs may well put objects on the stack if they detect that they can (for instance, when the object instance is only used within the method and bytecode analysis by the JVM shows that it’s impossible for there to be an outstanding reference to it when the method exits).