Skip to content

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

Closed

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]

Activity

  1. added
    a:false-negative
    on Jul 4, 2025
  2. changed the title [-][java] AvoidArrayLoops false-negative when break inside switch statement[/-] [+][java] AvoidArrayLoops: False negative when break inside switch statement[/+] on Dec 24, 2025
  3. added this to the 7.20.0 milestone on Dec 24, 2025
  4. added 2 commits that reference this issue on Dec 24, 2025
  5. added a commit that references this issue on Feb 10, 2026
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