• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

stack vs heap

 
Poonam Gulve
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I have very basic doubts.. what is the difference between stack and heap? isnt the stack a part of heap?? or it is somewhere else situated ?? and what are the things stored on heap and stack ( like local or instance variables or methods ) ??

Thanks in advance..

Regards,
Poonam
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Java Ranch,

The stack stores local variable for methods. There is a stack for each active thread.

The heap stores objects.

The methods themselves, the byte code, is stored in a special area along with static variables.

Some object reference variables are stored in the stack (if they are local variables). Some object reference variables are stored in the heap (if one object has a reference to another).

Kaydell
 
Poonam Gulve
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Kaydell,
Thanks for the explaination..

Does the GC clears the stack when the method is returned?? and how can a method return a value of a local variable when it(local var. ) doesnt hv scope after the method returns ??
 
Rajasekhar Pentakota
Ranch Hand
Posts: 38
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stack will be cleared by garbage collectors after returning or leaving the method. The value returned by the method is sent to the method caller.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no need to "clear" the stack. The stack contains parameters or local variables which are primitives or object references. When a method returns, the stack pointer just bumps back to where it was before the method call. Any parameters and local variables are now beyond the pointer.

When GC goes looking for references to objects it can't look in the stack beyond the pointer because it can't tell what that data is. A reference out there is not a reference any more, it's just some bits that might just as well be a few bits out of an int or double. Even if we could find a reference out there, it is now out of scope and doesn't factor into GC any more.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic