0

How does this code produce an IndexOutOfBoundsException?

int arr[] = new int[5]; for(int i = 0; i <= 5; ++i) arr[i] = i;

6th Aug 2019, 4:56 PM
Samuel
Samuel - avatar
1 Answer
+ 1
An array of size 5: [0] = 1st element [1] = 2nd element [2] = 3rd element [3] = 4th element [4] = 5th element so trying to call [5] would be attempting to retrieve the 6th element in an array with a size of 5, which is an IndexOutOfBounds. Your for loop condition should read i<5
6th Aug 2019, 5:17 PM
Jake
Jake - avatar