Skip to content

[java] ForLoopCanBeForeach: inconsistent detection between i += 1 and i = i + 1 update forms #6692

@Chordrain

Description

@Chordrain

Affects PMD Version: 7.24.0

Rule: ForLoopCanBeForeach — https://docs.pmd-code.org/latest/pmd_rules_java_bestpractices.html#forloopcanbeforeach

Description:

The ForLoopCanBeForeach rule correctly flags standard for loops that can be coverted into enhanced for-each loops when the update expression uses i++ or i += 1. However, it fails to detect the violation (resulting in a False Negative) when the update expression is written as a direct assignment i = i + 1, even though the logic is semantically identical.

Code Sample demonstrating the issue:

import java.util.List;

public class Sample {
    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5, 6);

        // Case 1: Flagged correctly by ForLoopCanBeForeach
        for (int i = 0; i < list.size(); i += 1) {
            System.out.println(list.get(i));
        }

        // Case 2: NOT flagged (False Negative)
        for (int i = 0; i < list.size(); i = i + 1) {
            System.out.println(list.get(i));
        }
    }
}

Expected outcome: PMD should report a violation at line 13, but doesn't. This is a false-negative.

Running PMD through: CLI

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of code

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions