my dog learned polymorphism*
The moose likes Beginning Java and the fly likes stack vs heap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "stack vs heap" Watch "stack vs heap" New topic
Author

stack vs heap

Poonam Gulve
Greenhorn

Joined: Aug 13, 2007
Posts: 16
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


Regards,<br />Poonam Gulve
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

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

Joined: Aug 13, 2007
Posts: 16
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

Joined: Aug 28, 2007
Posts: 38

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.


Thanks
Raja
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
 
subject: stack vs heap