Skip to content

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

Closed

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

Activity

  1. added
    a:false-negative
    on May 17, 2026
  2. qwerty7878 commented on May 27, 2026

    @qwerty7878
    Contributor

    I'm working on a fix for this.

  3. added this to the 7.26.0 milestone on May 31, 2026
  4. added a commit that references this issue on May 31, 2026
    8a740a4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negative

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions