Array index out of boundsÂķ
ID: java/index-out-of-bounds
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- quality
- reliability
- correctness
- exceptions
- external/cwe/cwe-193
Query suites:
- java-code-quality.qls
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
When accessing an array element, one must ensure that the index is less than the length of the array. Using an index that is greater than or equal to the array length causes an ArrayIndexOutOfBoundsException.
RecommendationÂķ
Ensure that the index is less than the array length.
ExampleÂķ
The following example causes an ArrayIndexOutOfBoundsException in the final loop iteration.
for (int i = 0; i <= a.length; i++) { // BAD
sum += a[i];
}
The condition should be changed as follows to correctly guard the array access.
for (int i = 0; i < a.length; i++) { // GOOD
sum += a[i];
}
ReferencesÂķ
Java API Specification: ArrayIndexOutOfBoundsException.
Common Weakness Enumeration: CWE-193.