Search code examples
javaarrays

Do Java arrays have a maximum size?


Is there a limit to the number of elements a Java array can contain? If so, what is it?


Solution

  • Using

    OpenJDK 64-Bit Server VM (build 15.0.2+7, mixed mode, sharing)
    

    ... on MacOS, the answer seems to be Integer.MAX_VALUE - 2. Once you go beyond that:

    cat > Foo.java << "END"
    public class Foo {
      public static void main(String[] args) {
        boolean[] array = new boolean[Integer.MAX_VALUE - 1]; // too big
      }
    }
    END
    java -Xmx4g Foo.java
    

    ... you get:

    Exception in thread "main" java.lang.OutOfMemoryError:
      Requested array size exceeds VM limit