Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why negative size of array is not a compilation error but throws java.lang.NegativeArraySizeException

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.

like image 337
Rajni Kewlani Avatar asked Feb 27 '18 13:02

Rajni Kewlani


Video Answer


1 Answers

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.

like image 179
Sergey Kalinichenko Avatar answered Sep 22 '22 10:09

Sergey Kalinichenko