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.