Added changes to demonstrate max array size

This commit is contained in:
Amitabh.Tiwari 2021-04-24 16:16:26 +05:30
parent 96e97ae79b
commit 3c65d2e8e7
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.format("Max-Size", Integer.MAX_VALUE - i);
} 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"));
}
}
}