Skip to content

[java] UnusedLocalVariable: false-positive with multiple for-loop indices #4518

@adangel

Description

@adangel

Affects PMD Version: 6.x

Rule: UnusedLocalVariable

Description:

Index variables of for loops should be ignored by this rule. This works if a single index is used, but for multiple variables, a false positive violation is reported.

Note: This is already fixed with PMD 7.0.0-rc1.
Found via #3123.

Code Sample demonstrating the issue:

public class UnusedLocalVarsMultiple {
    public void sample1() {
        int a = 0, b = 1; // a and b unused (line 3)
    }
    public void sample2() {
        int a = 0, b = a; // only b unused (line 6)
    }
    public void sample3() {
        for (int i = 0; i < 10; i++); // i is loop index, is used and should be ignored
    }
    public void sample4() {
        for (int i = 0, j = 0; i < 10; i++, j++); // i and j are loop indices, both are used (line 12)
    }
    public void sample5() {
        for (int i = 0, j = 0; i < 10; i++); // i and j are loop indices, but j is not used (line 15)
    }
}

Expected outcome:

PMD reports a violation at line 12, but that's wrong. That's a false positive.

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    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