Java memory (Stack) allocation for local variables

前端 未结 3 1805
傲寒
傲寒 2020-12-05 05:25

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
3条回答
  •  独厮守ぢ
    2020-12-05 06:03

    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.

提交回复
热议问题