Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array length less than 0?

Tags:

java

arrays

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?

like image 864
corsiKa Avatar asked Jul 17 '12 20:07

corsiKa


People also ask

Can an array length be less than 0?

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.

Does array length start 0 or 1 Java?

The indexes of elements in a Java array always start with 0 and continue to the number 1 below the size of the array.

Can an array have length 0 Java?

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.

Can array length negative?

Array dimensions cannot have a negative size.


1 Answers

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.

like image 171
tskuzzy Avatar answered Oct 05 '22 22:10

tskuzzy