Alex Rivera | Logout

Java "new String[-1]" passes compilation. How come?

Asked 2012-05-17T13:11:05.500
26

While fiddling around in Java, I initialized a new String array with a negative length. i.e. -

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

To my surprise, the compiler didn't complain about it. Googling didn't bring up any relevant answers. Can anyone shed some light on this matter?

Many thanks!

Edit
Report

2 Answers

2

I see no reason why this couldn't be flagged up at compile time (at least as a warning), since this unconditionally throws NegativeArraySizeException when executed.

I've done some quick experiments with my compiler, and it seems surprisingly relaxed about this sort of thing. It issues no warning about integer divide by zero in constant expressions, out-of-bounds array access with constant indices etc.

From this I conclude that the general pattern here is to trust the programmer.

answered 2012-05-17T13:18:20.507
0

Java compiler takes an integer as the length of an array. It can be a variable or a compile-time constant. The length of an array is established when the array is created. After creation, its length is fixed.

The compiler should flag a negative compile-time constant as the length of an array. It just does not do so . If the length is a negative number you will get a NegativeArraySizeException at run time.

answered 2012-05-17T13:18:15.340

Your Answer