educative.io

Defining and initializing arrays in one step

If I initialize the array
for eg:

int a[] = {1, 4, 6, -2, 0, 9}

// Then if I add a[7] = 40, and try to print the value of a[7] it shows 40.
// but if I check the size of the array after that it would show 24,

My question is why 24 why not 32 ?

Size of array a is 6. You cannot access index 7 because it doesn’t exist. If you do, you’ll get an exception -

jshell> int a[] = {1, 4, 6, -2, 0, 9}
a ==> int[6] { 1, 4, 6, -2, 0, 9 }

jshell> a[7] = 40;
|  Exception java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6
|        at (#2:1)