Skip to content

[java] NullAssignment: False positive when assigning null to a final field in a constructor #6276

Closed

Description

@Vampire

Affects PMD Version: 7.18.0

Rule: NullAssignment

Description:

If you have a final field that might be null or not, depending on the called constructor or depending on the arguments given to the constructor, you must set it to null explicitly in the constructor.
If you set it at declaration time, you cannot set it to a different value.
So assigning null to a final field in a constructor should not trigger a finding.

This does sometimes work as expected for example when directly assigning null, but if it is done as part of a ternary expression for example, the rule complains.

Code Sample demonstrating the issue:

https://github.com/Vampire/command-framework/blob/4e8f3137014399bc3e0673077239dbd641b63b20/src/main/java/net/kautler/command/api/Version.java#L95

import java.time.Instant;

public class Version {
    private final Instant buildTimestamp;

    public Version(String buildTimestamp) {
        this.buildTimestamp = "$buildTimestamp".equals(buildTimestamp) ? null : Instant.parse(buildTimestamp);
    }
}

Expected outcome:

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

Running PMD through: Gradle

Activity

  1. added
    a:false-positive
    on Nov 26, 2025
  2. mrclmh commented on Nov 27, 2025

    @mrclmh
    Contributor

    Extracted example:

    import java.time.Instant;
    
    public class Version {
        private final Instant buildTimestamp;
    
        public Version() {
            String buildTimestamp = "1764222289";
            this.buildTimestamp = "$buildTimestamp".equals(buildTimestamp) ? null : Instant.parse(buildTimestamp);
        }
    }
  3. mrclmh commented on Nov 28, 2025

    @mrclmh
    Contributor

    Another ternary problem mentioned here #1050 (comment).

  4. changed the title [-][java] `NullAssignment` should not report assigning `null` to a `final` field in a constructor[/-] [+][java] NullAssignment: False positive when assigning `null` to a `final` field in a constructor[/+] on Dec 19, 2025
  5. added this to the 7.20.0 milestone on Dec 19, 2025
  6. added a commit that references this issue on Dec 19, 2025
  7. added a commit that references this issue on Dec 19, 2025
    f2b2f7f
  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-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions