FP java:S2259 Optional and Nullability

  • SonarQube Community Build v25.10.0.114319
  • Java Code
  • Rule S2259 Null pointers should not be dereferenced

S2259 reports two false positive issue about potential NullPointerExceptions for the the following Java code:

package org.example;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.Optional;

@NullMarked
public abstract class S2259Optional {

  @Nullable
  public String a(@Nullable String s) {
    return Optional.ofNullable(s)  // FP: A "NullPointerException" could be thrown; "ofNullable()" can return null.
            .map(this::b)          // FP: A "NullPointerException" could be thrown; "map()" can return null.
            .orElse(null);
  }

  @Nullable
  abstract String b(@Nullable String s);
}

Optional#ofNullable and Optional#map never return null but an instance of Optional. Still S2259 raises issues for both.

I’ve attached the above source as minimal maven project.

test.zip (1.9 KB)

Cheers
Andreas

This one seems to be fixed v25.11.0.114957. I cannot reproduce it anymore.