Optional.ofNullable + Optional value should only be accessed after calling isPresent()

Due to some reason, our optional value can be null. So that is why we are using the below statement.

if(Optional.ofNullable(aliMnsId).isPresent()){
aliMnsId.get()
}

In that case Sonarqube should not throw this error “Optional value should only be accessed after calling isPresent()”

Hi,

The code still needs a call to aliMnsId.isPresent(). See this example:

Optional<String> aliMnsId = Optional.empty();
if (Optional.ofNullable(aliMnsId).isPresent()) {
    aliMnsId.get();
}

It causes the exception:

Exception java.util.NoSuchElementException: No value present
        at Optional.get (Optional.java:143)

And to avoid this error, you need a aliMnsId.isPresent() as SonarQube suggests…

if (Optional.ofNullable(aliMnsId).isPresent() && aliMnsId.isPresent())

But at this point, you could simply write if (aliMnsId != null && aliMnsId.isPresent())

1 Like

Thanks for the reply. I understand your point regarding exception. I will do the below check.
if (Optional.ofNullable(aliMnsId).isPresent() && aliMnsId.isPresent())

But if you put this “(aliMnsId != null && aliMnsId.isPresent())” then Sonarqube will give error “null” should not be used with "Optional"