Error in this program for int array Can anyone explain why these two cases behave differently?
class MainOutOfMemoryError {
/*
case1:doesn't give me any error
static final int s = 1024 * 1024 * 1024 * 1024 * 1024;
public static void main(String[] args) {
// we cant declare local variables as static
int[] i = new int[s];
System.out.println(s);
}
*/
// case2:gives error
static final int SIZE = 2 * 1024 * 1024;
public static void main(String[] a) {
int[] i = new int[SIZE];
System.out.println(SIZE);
}
}
From your comment
in Case1,it is showing sopln(s) prints 0 but in case 2 it prints actual Size ,WHY ?
In your first case, integer overflow happened and the result of s is 0
static final int s = 1024 * 1024 * 1024 * 1024 * 1024;
// s value is 0 because of overflow
That is kind of writing
int[] i = new int[0];
Where as in second case the result s is 2097152 a valid integer and you run out of memory while allocation of memory for integers in array.
So you are trying to do
int[] i = new int[2097152];
Which try to allocate the memory 67108864 bits.
I'm kind of clues here that, what makes you out of memory since that bits are equals to 8.388608MB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With