Skip to content

[java] UnusedLocalVariable: False positive for pattern variable in for-each without braces #6328

Closed

Description

@FabioMarangonSMI

Affects PMD Version: 7.19.0

Rule: UnusedLocalVariable

Description:
using an instanceof with a pattern variable inside a for-each without brackets gives a false positive

Code Sample demonstrating the issue:

public void test() {
	Object[] array = {1, "a"};
	for(Object o : array)
		if(o instanceof String s)
			System.out.println(s);
	return;
}

Expected outcome:
Variable s should not be reported as unused. If i use the brackets on the for-each, the warning disappears.

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

Running PMD through: Maven

With this code the warning is not reported:

public void test() {
	Object[] array = {1, "a"};
	for(Object o : array) {
		if(o instanceof String s)
			System.out.println(s);
	}
	return;
}

Activity

  1. added
    a:false-positive
    on Dec 16, 2025
  2. added
    in:symbol-table
    on Dec 16, 2025
  3. changed the title [-][JAVA] UnusedLocalVariable instanceof pattern variable inside for-each without brackets[/-] [+][java] UnusedLocalVariable instanceof pattern variable inside for-each without brackets[/+] on Dec 18, 2025
  4. mdhamed238 commented on Dec 19, 2025

    @mdhamed238
    Contributor

    I am on it.

  5. changed the title [-][java] UnusedLocalVariable instanceof pattern variable inside for-each without brackets[/-] [+][java] UnusedLocalVariable: False positive for pattern variable in for-each without braces[/+] on Dec 24, 2025
  6. added this to the 7.20.0 milestone on Dec 24, 2025
  7. added a commit that references this issue on Dec 24, 2025
    cf7871e
  8. 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-positivein:symbol-table

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions