8

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
user
  • 867
  • 9
  • 21

1 Answers1

8

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • This is a [Feynman-esque answer](https://www.youtube.com/watch?v=36GT2zI8lVA): *I can tell you what, but I can't tell you **why***. This doesn't give a reason why it isn't done at compile time; there is no "reason", in all likelihood, other than they just didn't see the need to. – Andy Turner Feb 27 '18 at 13:31
  • 1
    @AndyTurner That's exactly what I think is happening here. I was editing to mention this at the bottom. Thanks for the comment! – Sergey Kalinichenko Feb 27 '18 at 13:36
  • @AndyTurner considering how many little optimizations are done by `javac` and the fact that this is un-common, probably they never felt the need to actually do it – Eugene Feb 27 '18 at 14:10