I was working on arrays today and suddenly I came across a scenario throwing unexpected exceptions.
If you look at the code below , I think it must throw ArrayIndexOutOfBoundsException
, but surprisingly it is throwing IllegalArgumentException
instead:
import java.util.Arrays;
public class RangeTest {
public static void main(String[] args) {
int[] a = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] b = Arrays.copyOfRange(a, Integer.MIN_VALUE, 10);
// If we'll use Integer.MIN_VALUE+100 instead Integer.MIN_VALUE,
// OutOfMemoryError will be thrown
for (int k = 0; k < b.length; k++)
System.out.print(b[k] + " ");
}
}
Can anybody help me and let me know if I am mistaken?
copyOfRange(short[] original, int from, int to) method copies the specified range of the specified array into a new array. The final index of the range (to), which must be greater than or equal to from, may be greater than original.
fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Well, the Javadoc says :
Throws:
ArrayIndexOutOfBoundsException - if from < 0 or from > original.length
IllegalArgumentException - if from > to
Looking at the implementation, you can see that you got an IllegalArgumentException
exception instead of ArrayIndexOutOfBoundsException
due to int
overflow :
public static int[] copyOfRange(int[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
int[] copy = new int[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
This code thinks that from
> to
because to-from
caused int overflow (due to from
being Integer.MIN_VALUE
), which resulted in a negative newLength
.
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