Merge pull request #10696 from amitiw4u/BAEL-4919-MaxSizeArray

Added changes to demonstrate max array size
This commit is contained in:
Greg 2021-05-27 14:39:35 -04:00 committed by GitHub
commit 2a9d69a5fc
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package com.baeldung.array;
public class MaxSizeArray {
public static void main(String... strings) {
for (int i = 2; i >= 0; i--) {
try {
int[] arr = new int[Integer.MAX_VALUE - i];
System.out.println("Max-Size : "+ arr.length);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.arrays;
import org.junit.Assert;
import org.junit.Test;
public class MaxArrySizeUnitTest {
@Test
public void whenInitialArrayMoreThanMaxSize_thenThrowArray() {
boolean initalized = false;
try {
int[] arr = new int[Integer.MAX_VALUE - 1];
initalized = true;
} catch (Throwable e) {
Assert.assertTrue(e.getMessage().contains("Requested array size exceeds VM limit"));
}
Assert.assertFalse(initalized);
}
@Test
public void whenInitialArrayLessThanMaxSize_thenThrowArray() {
int[] arr = null;
try {
arr = new int[Integer.MAX_VALUE - 2];
} catch (Throwable e) {
Assert.assertTrue(e.getMessage().contains("Java heap space"));
}
}
}