Is there a limit to the number of elements a Java array can contain? If so, what is it?
I tried to create a byte array like this
byte[] bytes = new byte[Integer.MAX_VALUE-x];
System.out.println(bytes.length);
With this run configuration:
-Xms4G -Xmx4G
And java version:
Openjdk version "1.8.0_141"
OpenJDK Runtime Environment (build 1.8.0_141-b16)
OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)
It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2
Values above that give
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Main.main(Main.java:6)