Out of memory exception in Java:


Whenever you create an object in Java it is stored in the heap area of the JVM. If the JVM is not able to allocate memory for the newly created objects an exception named OutOfMemoryError is thrown.

This usually occurs when we are not closing objects for long time or, trying to act huge amount of data at once.

There are 3 types of errors in OutOfMemoryError −

  • Java heap space.
  • GC Overhead limit exceeded.
  • Permgen space.

Example 1

 Live Demo

public class SpaceErrorExample {
   public static void main(String args[]) throws Exception {
      Float[] array = new Float[10000 * 100000];
   }
}

Output

Runtime exception

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
   at sample.SpaceErrorExample.main(SpaceErrorExample.java:7)

Example 2

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class OutOfMemoryExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Getting the Iterator object of the ArrayList
      ListIterator<String> it = list.listIterator();
      while(it.hasNext()) {
         it.add("");
      }
   }
}

Output

Runtime exception

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
   at sample.SpaceErrorExample.main(SpaceErrorExample.java:7)

Updated on: 06-Sep-2019

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements