简体   繁体   中英

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);
    }
}

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

The int 1024 * 1024 * 1024 * 1024 * 1024 is actually 0 due to int overflow.

int arithmetic works modulo 2^32 . Since 1024 = 2^10 , the true mathematical value of that product is 2^50 . Since 50 > 31 , s == 0 .

In the first case you are allocating an array of length 0. In the second case it has length over 2 million.

For your first example, 1024 * 1024 * 1024 * 1024 * 1024 , Google calculator gives 1.1258999e+15 . The Java Primitive Data Types tutorial says (in part)

int : By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of 2^31-1

According to Google calculator, the maximum value of an int is thus 2147483647. Which means your value overflows int . That's why it worked.

If you test it like,

int i = 1024 * 1024 * 1024 * 1024 * 1024;
System.out.println(i);

You'll see that the result is 0 .

I think you mean the opposite: case 1 gives an error and the 2nd doesn't:

It is not the array that is causing the memory overflow but the variable SIZE which is an int with a max value of around 2 billion, change it to long and the problem is solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM