InterviewSolution
| 1. |
What is the difference between the stack and heap memory? Why a stack is used for the purpose of storing the local variables? |
|
Answer» STACK memory is used to create the local variables and object references while executing a method by a thread. This means each thread has a SEPARATE stack and set of local variables. Stack doesn’t contain the actual objects - it only contains the references. The memory space for the actual objects is allocated in the heap memory. Heap memory is composed of a number of parts - young generation (EDEN and Survivor space) and old generation. For each method CALL JVM creates a new stack frame containing the local variables. Maintaining them as a stack helps to retrieve the most recent stack frame i.e., the set of variables of the caller method easily when a method returns. |
|