I am learning java and right now i am stuck at memory allocation of object's and local variables. can any one illustrate or clear some of my doubts??
Thanks Mahaveer
Java Runtime creates Stack memory to be used by main() method thread when it is found at line 1. At line 2, a primitive local variable is created, which is stored in the Stack memory of main() method. Since an Object is created at line 3, it's created in Heap memory and the reference for it is stored in Stack memory.
The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame.
Local variables are stored on the stack. That includes primitives (such as int ) and the references to any objects created.
For local variables, the memory they consume is on the stack. This means that they must have a fixed size known at compile time, so that when the function is called, the exact amount of memory needed is added to the stack by changing the value of the stack pointer.
Every thread has it's own stack.
new
, an object is created on the heap.int
) and the references to any objects created. The actual objects themselves aren't created on the stack, as I mentioned when you use new
they'll be created on the heap. I have question that weather a new STACK is being created for each method??
The same stack is being used when a method is called. A method will create it's own little section on the stack called a "stack frame" that's used to hold it's local variables.
It's just like a stack of plates, when a method is called a plate is added to the top of the stack (a stack frame), and when that method ends the plate is removed from the stack. All of that method's local variables will be destroyed with it, but the actual objects created with new
won't.
The JVM's garbage collector will look after destroying objects on the heap (the one's created with new
) when it sees you no longer need them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With