Inspectopedia Help

Assignment to 'for' loop parameter

Reports assignment to, or modification of a for loop parameter inside the body of the loop.

Although occasionally intended, this construct may be confusing and is often the result of a typo or a wrong variable being used.

The quick-fix adds a declaration of a new variable.

Example:

for (String s : list) { // Warning: s is changed inside the loop s = s.trim(); System.out.println("String: " + s); }
for (String s : list) { String trimmed = s.trim(); System.out.println("String: " + trimmed); }

Assignments in basic for loops without an update statement are not reported. In such cases the assignment is probably intended and can't be easily moved to the update part of the for loop.

Example:

for (int i = 0; i < list.size(); ) { if (element.equals(list.get(i))) { list.remove(i); } else { // modification of for loop parameter is not reported // as there's no update statement i++; } }

Use the Check enhanced 'for' loop parameters option to specify whether modifications of enhanced for loop parameters should be also reported.

Inspection options

Here you can find the description of settings available for the Assignment to 'for' loop parameter inspection, and the reference of their default values.

Check enhanced 'for' loop parameters

Default: Selected

Inspection Details

By default bundled with:

IntelliJ IDEA 2024.1, Qodana for JVM 2024.1,

Can be installed with plugin:

Java, 241.14841

Last modified: 12 March 2024