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?
1 Answer. Show activity on this post. Every Array has a non-configurable "length" property whose value is always a non-negative integral Number whose mathematical value is less than 2^32. So either check is perfectly fine, and both will have the same result for all arrays.
The indexes of elements in a Java array always start with 0 and continue to the number 1 below the size of the array.
Java allows creating an array of size zero. If the number of elements in a Java array is zero, the array is said to be empty. In this case you will not be able to store any element in the array; therefore the array will be empty.
Array dimensions cannot have a negative size.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With