I wrote some code in java:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array:");
int size = sc.nextInt();
int[] intArray = new int[size];
for (int i = 0; i < size; i++) {
System.out.println("Please enter int value at index " + i + ":");
intArray[i] = sc.nextInt();
}
System.out.println("Enter array index to get the value:");
int index = sc.nextInt();
sc.close();
System.out.println("Value at " + index + " = " + intArray[index]);
But it gives me error:
Enter size of int array:
3
Please enter int value at index 0:
1
Please enter int value at index 1:
2
Please enter int value at index 2:
3
Enter array index to get the value:
4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.journaldev.exceptions.ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:23)
What is the problem in my code and why am I getting this kind of error?