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?