- 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.
- 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.
- The stack mainly stores some essential data type variables (byte, short, int, long, float, double, Boolean, char) and object references.
- 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.