The difference between heap and stack in Java

By | June 17, 2020

Heap

  1. Java’s heap is a runtime data area, and objects of classes allocate space from the heap. These objects are created by instructions such as new and destroyed by the garbage collector.
  2. The advantage of the heap is that it can allocate memory space dynamically. It is unnecessary to tell the compiler how much memory space is needed because it is allocated dynamically at runtime. However, the disadvantage is that the access speed is slow due to the need to allocate memory at runtime dynamically.  

Stack

  1. The stack mainly stores some essential data type variables (byte, short, int, long, float, double, Boolean, char) and object references.
  2. The advantage of the stack is that access speed is faster than the heap, and stack data can be shared. However, the disadvantage is that how much memory space is occupied by the data stored in the stack needs to be determined at compile-time, which lacks flexibility.