JAVACriticalRuntime ErrorApril 23, 2026

Runtime Error

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

What This Error Means

This error occurs when the Java Virtual Machine (JVM) runs out of memory, typically due to a large heap size or insufficient heap space. It can also be caused by a memory leak in the program.

Why It Happens

This error can happen when the JVM is not configured to allocate enough memory for the program. It can also occur when the program uses more memory than it is supposed to, causing the JVM to run out of space. This can happen due to various reasons such as infinite loops, large data structures, or memory leaks.

How to Fix It

  1. 1To fix this error, you can try the following steps:
  2. 21. Increase the heap size by passing the -Xmx flag to the JVM.
  3. 32. Optimize the code to use less memory, such as by using more efficient data structures or algorithms.
  4. 43. Check for memory leaks in the program and fix them.
  5. 54. Use the VisualVM tool to profile the application and identify memory usage patterns.
  6. 6For example, if your program is running on a 64-bit JVM, you can try increasing the heap size by adding the following flag to the Java command:
  7. 7java -Xmx1024m MyProgram
  8. 8This will increase the heap size to 1024 megabytes.

Example Code Solution

❌ Before (problematic code)
Java
public class MemoryLeak { 
    public static void main(String[] args) { 
        List<byte[]> list = new ArrayList<>(); 
        while (true) { 
            list.add(new byte[1024 * 1024]); 
        } 
    } 
}
✅ After (fixed code)
Java
public class MemoryOptimized { 
    public static void main(String[] args) { 
        List<byte[]> list = new ArrayList<>(); 
        for (int i = 0; i < 100; i++) { 
            list.add(new byte[1024 * 1024]); 
        } 
        // Clear the list after use 
        list.clear(); 
    } 
}

Fix for Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Related JAVA Errors

Related JAVA Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error