by BehindJava

Heap and Stack Memory Errors in Java

Home » java » Heap and Stack Memory Errors in Java

In this tutorial, we will see the basic errors that can be in a heap or stack memory in Java.

  • Heap memory - This is a special memory area where java objects are stored.
  • Stack memory - Temporary memory area to store variables when method invoked.

The main exception that describes the problem with the heap memory in java.lang.OutOfMemoryError.

Java Heap Space

Java program is failed to allocate a new object in the heap memory area.

GC Overhead Limit Exceeded

Java program is spending too much time on garbage collection. Thrown in case garbage collection takes 98% of program time and recover less than 2% of a memory space


public class OutOfMemoryErrorDemo {
    public static void main(String[] args) {
        int i = 0;
        List<String> stringList = new ArrayList<>();
        while (i < Integer.MAX_VALUE) {
            String generatedString = new String( "Some string generated to show out of memory error example " + i);

stringList contains a link to our generated strings, that’s why GC can’t delete our generated strings from memory and GC tries to delete any other garbage in the application, but that’s not enough.

Requested Array Size Exceeds VM Limit

Tries to allocate an array when a heap space is not enough.

public class OutOfMemoryErrorDemo {
    public static void main(String[] args) {
        // we try to create too long array
        long[] array = new long[Integer.MAX_VALUE];


The exception is thrown with that message when there is no space in the metaspace area for class data information.

Request Size Bytes for Reason. Out of Swap Space?

Thrown when failed to allocate memory in the native heap or native heap close to exhaustion.

reason stacktracewithnativemethod

Java Native Interface or native method failed to allocate memory in heap.

  • StackOverFlowError - when there are too many method calls. Usually, the exception is thrown by the method that has recursion inside.

    public class StackOverFlowErrorDemo {
       public static void main(String[] args) {
    public static int recursiveMethod(int i) {
        // it will never stop and it allocates all stack memory
        return recursiveMethod(i);