Skip to content

[java] AvoidArrayLoops: False negative when break inside switch statement #5877

@csrma

Description

@csrma

Affects PMD Version: 7.15.0

Rule: AvoidArrayLoops

Description:
The AvoidArrayLoops is not triggered when there is a break statement inside a switch-case statement in the loop. In the following code, if we remove/comment out the break statement, the issue is triggered at line 7. I suspect the reason could be that the XPath expression explicitly checks [not(.//BreakStatement)], regardless of whether the break is exiting the loop or the switch statement.

Code Sample demonstrating the issue:

import java.util.Arrays;

class ArrayLoopBugDemo {

    public int[] showBug(int[] source, int condition) {
        int[] destination = new int[source.length];
        for (int i = 0; i < source.length; i++) {    // should raise AvoidArrayLoops here
            destination[i] = source[i];
            switch (condition) {
                case 0:
                    System.out.println("This is an unreachable switch case.");
                    break;
            }
        }
        return destination;
    }

    public static void main(String[] args) {
        ArrayLoopBugDemo demo = new ArrayLoopBugDemo();
        
        int[] dest = demo.showBug(new int[]{1, 2, 3, 4, 5}, 1);
    }
}

Expected outcome:

PMD should report a violation at line 7, 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

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions