Skip to content

[java] ExhaustiveSwitchHasDefault: False positive with final fields not initialized in constructor #5670

Closed

Description

@kohlschuetter

Affects PMD Version: 7.12.0

Rule: ExhaustiveSwitchHasDefault
https://pmd.github.io/pmd/pmd_rules_java_bestpractices.html#exhaustiveswitchhasdefault

Description:
ExhaustiveSwitchHasDefault cannot be applied because the compiler complains that a final field was not initialized (for the impossible, missing default case).

Moreover, in combination with CheckStyle, which has a "MissingSwitchDefault" rule, this new PMD rule is impossible to apply.

Code Sample demonstrating the issue:

import java.io.PrintStream;

public class Test {
  private final PrintStream out;

  public enum ProcessStream {
    STDOUT,
    STDERR
  }

  public Test(ProcessStream stream) {
    switch (stream) {
      case STDOUT:
        this.out = System.out;
        break;
      case STDERR:
        this.out = System.err;
        break;
      default:
        // Without this "default" section, Eclipse complains with:
        // The blank final field out may not have been initialized.
        // Note that a problem regarding missing 'default:' on 'switch' has been suppressed,
        // which is perhaps related to this problem
        throw new IllegalStateException();
    }
  }
}

Expected outcome:

Since the assumption that the compiler is doing its job right is wrong, I think we should at least work around this limitation, or disable the rule by default.

Running PMD through: Maven

Activity

  1. added
    a:false-positive
    on Apr 10, 2025
  2. changed the title [-]ExhaustiveSwitchHasDefault issue with final fields not initialized in constructor[/-] [+][java] ExhaustiveSwitchHasDefault issue with final fields not initialized in constructor[/+] on Apr 10, 2025
  3. adangel commented on Apr 10, 2025

    @adangel
    Member

    Thanks for reporting. This is related to #5514, but is a slightly different edge case.

  4. added a commit that references this issue on Jul 15, 2026
    df58615
  5. added this to the 7.27.0 milestone on Jul 15, 2026
  6. changed the title [-][java] ExhaustiveSwitchHasDefault issue with final fields not initialized in constructor[/-] [+][java] ExhaustiveSwitchHasDefault: False positive with final fields not initialized in constructor[/+] on Aug 20, 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-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions