java does not allow to initialize an array with negative size. For example:
int[] arr = new int[-1];
If this is already known, why it throws NegativeArraySizeException
instead of compilation error? Just curious to know why java decides it to be thrown at runtime while it is known at compile time that it will fail.
This check could be performed at compile time only in situations when the size is specified as a constant expression. However, Java Language Specification requires this check to be done at run time:
15.10.2 Run-Time Evaluation of Array Creation Expressions
At run time, evaluation of an array creation expression behaves as follows:
[...]
- First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.
- Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then a
NegativeArraySizeException
is thrown.
In deciding if a certain check should be performed at compile-time or not the compiler design team considers costs and benefits of the new feature. Since the compile-time check would not replace a run-time check, but would be performed in addition to it, the added benefit is marginal. It does not mean, however, that the feature should not be implemented in a future version of the compiler, only that the language designers did not prioritize it high enough to be implemented now.
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