0

I was trying to create a int[] type array in Java with a user input based length. Below is the code for the same :

int[] change = new int[max+1];

When the value of max = 2147483647, the compiler shows the below error code : type here

java.lang.NegativeArraySizeException: -2147483648

I know that the upper limit for int in Java is -2147483648 to 2147483647 (-231 to 231-1), but why is the size of array going negative with a addition (is it looping back to the lower limit?). The problem remains the same with long[] type array. So, does Java not support array size above 231-1 ?

  • *"is it looping back to the lower limit?"* - yes. – luk2302 Jan 04 '23 at 13:00
  • https://www.baeldung.com/java-arrays-max-size – Oskar Jan 04 '23 at 13:03
  • 1
    Why do you need an array that huge? I think you're confusing the size of the array with the size of each int stored in each cell of the array. They're not the same. – Stephan Branczyk Jan 04 '23 at 13:05
  • 1
    No. [JLS-10.4 Array Access](https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.4) says (in part) *Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values. An attempt to access an array component with a long index value results in a compile-time error. All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.* – Elliott Frisch Jan 04 '23 at 13:05

0 Answers0