What mechanism does Java use to efficiently check if the array element I'm trying to access is out of bounds. The one way I thought it could do it is by having metadata before the array in memory. But an if statement at each check would be quite inefficient in terms of time. So how does it actually do it?
Asked
Active
Viewed 575 times
-2
-
What makes you think it checks anything? Accessing an index out of bounds causes an Exception. – Jesse Webb Dec 17 '12 at 08:14
-
well does it actually check for the ArrayIndexOutOfBounds Exception? if so, why get an exception? – manas Dec 17 '12 at 08:14
-
2@JesseWebb the question is how does Java recognize that there is an attempt to access an index that does not belong to the array, so it can throw the AIOOB Exception. – SJuan76 Dec 17 '12 at 08:16
-
What can be more efficient than a `<` and `>` check, and can be evaluated at runtime? Short of "magic", I cannot think of anything. – SJuan76 Dec 17 '12 at 08:17
3 Answers
2
This is very famous piece of code because of Oracle vs Google battle:
private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex+")");
if (fromIndex < 0)
throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > arrayLen)
throw new ArrayIndexOutOfBoundsException(toIndex);
}
This method is called internally.

Nikolay Kuznetsov
- 9,467
- 12
- 55
- 101
-
@ Nikolay can you please let know what Oracle-Google battle has do with it, I am very curious. – Abubakkar Dec 17 '12 at 08:18
-
1@Abu, I have updated with just a random link. You can find much more by googling. – Nikolay Kuznetsov Dec 17 '12 at 08:20
0
Simple check as below would do,
int[] a = new int[2];
if (a.size >= index )
System.out.println("Item " + a[i]);

Jayamohan
- 12,734
- 2
- 27
- 41
-
1The question is not when the exception is launched, but how does the JVM recognize that an illegal access has been attempted (so it can throw the exception). – SJuan76 Dec 17 '12 at 08:18
0
It seems that it does literally check boundaries on each of *aload
, *astore
etc. instructions as described in JVM 7 specification.
If index is not within the bounds of the array referenced by arrayref, the (*astore,*aload,etc) instruction throws an ArrayIndexOutOfBoundsException
But how it is actually done is implementation specific.

nullpotent
- 9,162
- 1
- 31
- 42