Java array length less than 0?

Viewed 10171

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?

3 Answers
Related