xxxxxxxxxx
check the code if it is accesing the element at negative index
xxxxxxxxxx
Since in java the first position of an array is 0, if an array has
length 3 then the last element is in position 2.
Ex: array = [elem0, elem1, elem2] then the last elem is index 2
and the array has length 3
xxxxxxxxxx
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at Assignment4.main(Assignment4.java:11)
xxxxxxxxxx
import java.util.Random;
public class demo{
public static void main(String[]args){
Random rand=new Random();
int array[]=new int[10];
for(int i=0;i<array.length;i++){
array[i]=rand.nextInt(100);//random between 0 and 100
}
System.out.println(array[array.length]);// error java.lang.ArrayIndexOutOfBoundsException
// because index start 0 and end array.length
}
}