Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in this program for int array in two different situations behaves differently

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);
    }
}
like image 664
Ramesh Raj Avatar asked Sep 12 '26 06:09

Ramesh Raj


1 Answers

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

like image 180
Suresh Atta Avatar answered Sep 14 '26 19:09

Suresh Atta