1.

Heap vs Stack Memory in Java

Answer»

DETAILS about the heap space and stack memory in Java as well as their differences is given as follows:

Heap Space in Java

The heap space in Java is allocated the memory to the Objects and the JRE classes by the Java runtime. All the objects in the application are created in the heap space. The objects in the heap space are globally accessible from any place in the application and so they have a lifetime for the whole application execution.

The memory model of the heap space is divided into parts known as generations. The three generations are young generation, old generation and PERMANENT generation.

Stack Memory in Java

The Stack memory in Java is used for thread execution. Specific values are stored in the stack memory that are available for a short time. Also, stack memory may contain data references to objects getting referred from the method that are in the heap memory.

The order in Stack memory is Last In First Out (LIFO). A block is created in the stack memory for all the primitive values and references to other objects in a method when that method is invoked. After the end of the method, the memory block in the stack memory is free and can be used by another method.

Differences between Heap Space and Stack Memory

Some of the differences between stack memory and heap memory are given as follows:

  1. The stack memory management is DONE USING LIFO but it is more complicated for heap memory as that is used by the whole application.
  2. Stack memory is faster than heap memory as its memory allocation procedure is much more simple.
  3. The stack memory is only used by a thread whereas the heap memory is required by all the application parts.
  4. The stack memory is only accessible by the individual thread but the heap memory objects can be accessed globally.
  5. The stack memory is COMPARATIVELY short lived while the heap memory exists for the whole execution of the application.


Discussion

No Comment Found