Unclear about relationship between heap and stack

Just to make sure you understand the difference between Stack as a data structure, and a call stack used by a Java program to execute methods.

Stack as a data structure is just a collection of elements that are organized in FIFO order (first in first out) and implements two main methods - push() and pop(). Your program can make Stacks for everything, numbers, letters, Objects, but basically they serve a purpose similar to that of a simple array - to store and retrieve multiple items, - only accessed in a special order.

The call stack is another thing altogether. It's organized in the same manner as a Stack data structure - when a new item is added to it, it's pushed onto the top, and when it's removed, it's popped from the top as well. That's where the similarities end. The call stack stores information about the active method that's currently executing, along with all its variables (arguments and locals) and some other method information.

Every time a new method is invoked, a new stack frame is created, according to the information that is stored in a compiler-generated .classfile of a class that has this method, and pushed on top of the call stack. The stack frame size is computed at compile time depending on the number and size of the variables that the method uses - local variables and parameters that are passed to it.

Method's local variables are always stored on the stack. If it's a reference variable (like an array or an Object) - the reference (address) of this object is stored inside the stack frame - but the object itself is stored on the heap. No matter how huge your object is, its reference only takes 4 bytes. When the method returns, the frame is popped off the stack and all its variables disappear. If the method has created a bunch of Objects on the heap while it was running, and when returned, there was nothing else using and pointing to those Objects, they become eligible for garbage collection.

Here's an article that explains Java call stack in more detail

Reference(or as you call them, "complex") types in general can reach any size, that's true. (that's why you sometimes will get OutOfMemory error - Java will try to allocate heap space for some huge-ass object and it won't be enough). Objects can contain other Objects and they can contain other Objects and so on, - but eventually you will go all the way down to a primitive value.

/r/javahelp Thread