Why a negative array size is not a compilation error, but raises a java.lang.NegativeArraySizeException

java does not allow to initialize an array with a negative size. For instance:

int[] arr = new int[-1];

If this is already known, why does it throw NegativeArraySizeExceptioninstead of a compilation error? It's just curious to know why Java decides that it will be run at run time, while at compile time it is known that it will fail.

+4
source share
1 answer

This check can be performed at compile time only in situations where the size is specified as a constant expression. However, the Java Language Specification requires that this check be performed at runtime:

15.10.2

:

[...]

  • . - , .
  • . DimExpr , a NegativeArraySizeException.

, , . , , . , , , , .

+5

Source: https://habr.com/ru/post/1694179/


All Articles