You've just encountered the dreaded Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
after running your code. A seemingly successful computation abruptly halted. But what triggered this error?
Let's consider some code
import java.util.ArrayList;
public class OutOfMemory {
public static void main(String[] args) {
ArrayList<Integer> dataStore = new ArrayList<>();
long n = Integer.MAX_VALUE;
n++;
for (long i = 0; i < n; i++) {
dataStore.add(0);
}
System.out.println("Will never print this message");
}
}

Running the code above produces this exception:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.base/java.util.Arrays.copyOf(Arrays.java:3512) at java.base/java.util.Arrays.copyOf(Arrays.java:3481) at java.base/java.util.ArrayList.grow(ArrayList.java:237) at java.base/java.util.ArrayList.grow(ArrayList.java:244) at java.base/java.util.ArrayList.add(ArrayList.java:454) at java.base/java.util.ArrayList.add(ArrayList.java:467) at OutOfMemory.main(OutOfMemory.java:9)
But why?
Due to the 32-bit nature of Java's int
data type, the largest array you can create is restricted to Integer.MAX_VALUE
, or 2,147,483,647.
But this is an ArrayList why does this matter?
Although it provides dynamic resizing, an ArrayList
essentially uses an array internally. When the array is close to full, the ArrayList automatically creates a larger one.
Big data issues
If your computation requires storing more than 2,147,483,647 values, neither an array nor an ArrayList
is suitable.