Skip to content

[java] UseStandardCharsets: False negative when using lowercase standard charset names #6710

@mmnhgo

Description

@mmnhgo

Affects PMD Version:
PMD 7.24.0

Rule:

UseStandardCharsets

Description:
The UseStandardCharsets rule reports calls to Charset.forName(...) when the charset can be replaced by a constant from StandardCharsets, for example StandardCharsets.UTF_8.

However, the rule currently only matches exact uppercase string literals such as "UTF-8". It does not report semantically equivalent lowercase or mixed-case standard charset names, such as "utf-8" or "Utf-8".

According to the Java Charset specification, charset names are not case-sensitive. Therefore, Charset.forName("utf-8") resolves to the same standard UTF-8 charset as Charset.forName("UTF-8"). Since PMD already reports Charset.forName("UTF-8"), it should also report Charset.forName("utf-8").

Current behavior:

Charset.forName("utf-8")  -> no violation, exit code 0
Charset.forName("UTF-8")  -> violation reported, exit code 4

For the uppercase variant, PMD reports:

/tmp/ReproUseStandardCharsetsUpper.java:5: UseStandardCharsets: Please use StandardCharsets constants

This suggests that the rule is active and works for exact uppercase literals, but misses lowercase standard charset names. This is a false-negative.

Code Sample demonstrating the issue:

import java.nio.charset.Charset;

class ReproUseStandardCharsets {
    Charset charset() {
        return Charset.forName("utf-8"); // <-should report(FN)
    }
}

Expected outcome:

PMD should report a violation at line 5, but doesn't. This is a false-negative.

Expected replacement:

return StandardCharsets.UTF_8;

Running PMD through: CLI

Example command:

pmd check -d ReproUseStandardCharsets.java \
  -R category/java/bestpractices.xml/UseStandardCharsets \
  -f text --no-progress

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of code

    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