wood burning stoves 2.0*
The moose likes Java in General and the fly likes if vars are on stack, but cannot be outside of objs, and objs are always in the heap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "if vars are on stack, but cannot be outside of objs, and objs are always in the heap " Watch "if vars are on stack, but cannot be outside of objs, and objs are always in the heap " New topic
Author

if vars are on stack, but cannot be outside of objs, and objs are always in the heap

Guennadiy VANIN
Ranch Hand

Joined: Aug 30, 2001
Posts: 898


I have read

As per "Java 2 Certification Guide" -Simon Roberts etc. page 22, when ever a new object is created, it is stored on the heap however variable containing reference to it will be stored on stack.

made confusion in my head (like who was before a hen or an egg?)
An object almost always has reference-variables. Object is on the heap, but his internals are on the stack?
I do not quite understand what is the object, where it is and how it gc(-ed).
Does it mean that each object creation creates their own heap and stack, per each object?
[ January 07, 2003: Message edited by: yidanneuG ninaV ]

(Marilyn fixed link)
[ January 07, 2003: Message edited by: Marilyn de Queiroz ]
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
A local variable is stored on a stack related to the method that contains it. Such a variable only lives as long as the method is going. When the method is over, the stack is gone, and the variable is gone.
A local variable may REFERENCE an object (which is on the heap). When the local variable dies, if that is the ONLY reference to the object then the object is available for the gc.
The trick is not to confuse the variable with the object that it references. They are two separate things.
An object may ALSO contain variables, known as fields (because they are not local to any method). These variables exist until the object is gc'd.
Some fun reading:
Not all Variables are created Equal
How my Dog learned Polymorphism
(MUCH more fun than the JVM Specs )
[ January 07, 2003: Message edited by: Cindy Glass ]

"JavaRanch, where the deer and the Certified play" - David O'Meara
 
Don't get me started about those stupid light bulbs.
 
subject: if vars are on stack, but cannot be outside of objs, and objs are always in the heap
 
Similar Threads
GC behavior towards static objects
Static variables must store ?
Parent reference can't access child method but whats happenning here? CLEARED THANKS.
stack and heap variable
Stack/Heap: the Memory Allocation of Local Variables