Why is this an issue?

Optional acts as a container object that may or may not contain a non-null value. It is introduced in Java 8 to help avoid NullPointerException. It provides methods to check if a value is present and retrieve the value if it is present.

Optional is used instead of null values to make the code more readable and avoid potential errors.

It is a bad practice to use null with Optional because it is unclear whether a value is present or not, leading to confusion and potential NullPointerException errors.

How to fix it

There are a few ways to fix this issue:

Code examples

Noncompliant code example

public void doSomething () {
  Optional<String> optional = getOptional();
  if (optional != null) {  // Noncompliant
    // do something with optional...
  }
  Optional<String> text = null; // Noncompliant, a variable whose type is Optional should never itself be null
  // ...
}

@Nullable // Noncompliant
public Optional<String> getOptional() {
  // ...
  return null;  // Noncompliant
}

Compliant solution

public void doSomething () {
  Optional<String> optional = getOptional();
  optional.ifPresent(
    // do something with optional...
  );
  Optional<String> text = Optional.empty();
  // ...
}

public Optional<String> getOptional() {
  // ...
  return Optional.empty();
}

Resources

Documentation

Articles & blog posts