Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java memory (Stack) allocation for local variables

Tags:

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??

  1. I read about Heap and Stack Memory for Object's instance Variable's and Local Variable's. I have question whether a new STACK is being created for each method?? or for each class of a single stack is used by a whole class??
  2. I had read that ONE STACK is being created by every thread What is means

Thanks Mahaveer

like image 701
Mahaveer Muttha Avatar asked Nov 09 '11 07:11

Mahaveer Muttha


People also ask

When memory is allocated for local variables in Java?

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.

Are local variables allocated on the stack?

The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame.

Are local variables stored on the stack Java?

Local variables are stored on the stack. That includes primitives (such as int ) and the references to any objects created.

Where is memory allocated for local variables?

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.


1 Answers

Every thread has it's own stack.

  • Whenever you use new, an object is created on the heap.
  • Local variables are stored on the stack. That includes primitives (such as 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.

like image 131
AusCBloke Avatar answered Sep 28 '22 10:09

AusCBloke