Java array length less than 0?

arrays, java

Solution

No, this can never happen. The length is guaranteed to be non-negative as per the Java specifications.

The members of an array type are all of the following:

- The public final field length, which contains the number of components of the array. length may be positive or zero.

Source: JLS §10.7

As mprivat mentioned, if you ever try to create an array of negative size, a NegativeArraySizeException will be thrown.

Problem

I was going through an open source project where they were creating an output stream, and came across the following method: ``` @Override public void write(byte[] buffer, int offset, int length) { if (buffer == null) { throw new NullPointerException("buffer is null"); } if (buffer.length < 0) { // NOTE HERE throw new IllegalArgumentException("buffer length < 0"); } if (offset < 0) { throw new IndexOutOfBoundsException(String.format("offset %d < 0", offset)); } if (length < 0) { throw new IndexOutOfBoundsException(String.format("length %d < 0", length)); } if (offset > buffer.length || length > buffer.length - offset) { throw new IndexOutOfBoundsException(String.format("offset %d + length %d > buffer" " length %d", offset, length, buffer.length)); } } ``` So the `byte[] buffer` is just a normal old `byte[]`. We know it's not null. Is it even possible to make it have a length of less than 0? Like, could it be done with reflection and that's what they're guarding against?

Original source