java:S5411 complains about use of boxed boolean even though it cannot be null

SonarQube server v10.8 (100206)
SonarQube for IDE 10.14.1.80220

Here, var becomes Boolean. Sonar then complains about use of a boxed boolean in the if statement, even though it is not possible for it be null. No matter how the Optional is created/mapped/filtered, if the chain ends with an orElse(boolean), then it cannot be null, even though the return type is Boolean instead of the preferred boolean

var notNullable = Optional.ofNullable(null).orElse(false);
if (notNullable) {}

Of course, I could fix this by changing from var to boolean. But it shouldn’t be necessary.
For example, if I add an unnecessary null check, then Sonar doesn’t complain:

var notNullable = Optional.ofNullable(null).orElse(false);
if (notNullable == null) return;
if (notNullable) {}

Hello @lbenedetto
Thanks for reporting this issue.

What I see here is that .orElse is always boxing to Boolean, and in the first part of the code the if is receiving an Object that has not been checked against null, although I agree that following the code’s flow we know it will always be Boolean.False.

What the the rule is checking is if the first usage of the variable is a null checking. If so, all clear, if not the issue is reported.

But thanks to your report we will consider your suggestions.

Hello @lbenedetto

Here you have the issue created in our system with a similar case. We will work on that.
https://sonarsource.atlassian.net/browse/SONARJAVA-5146

Thanks for using and reporting, you help us to have better tools.

1 Like