what's the difference between the stack and the heap code example
Example 1: heap vs stack memory
Whenever an object is created, it’s always stored in the Heap space, and stack
memory contains the reference to it. Stack memory only contains local
primitive variables and reference variables to objects in heap space.
Objects stored in the heap are globally accessible whereas stack memory can’t
be accessed by other threads.
Memory management in stack is done in LIFO manner whereas it’s more complex in
Heap memory because it’s used globally.
Stack memory is short-lived whereas heap memory lives from the start till the
end of application execution.
Heap memory is used by all the parts of the application, stack memory is used
only by one thread of execution.
When stack memory is full, Java runtime throws
java.lang.StackOverFlowError When heap memory is full, it throws
java.lang.OutOfMemoryError: Java Heap Space error.
Stack memory is faster than heap memory.
Example 2: stack memory allocation c++
memory allocation