Java Boolean to boolean - I don't get it

  • Operating system: Windows 10
  • IDE name and flavor/env: Eclipse STS

This simple piece of code gives me a warning:

final Boolean cardEnabled = parseAndGet("card-enabled");
    cardEnabled == null ? false : cardEnabled.booleanValue()

Method parseAndGet() uses a map of properties and returns null, Boolean.TRUE or Boolean.FALSE.

Setter of readCard needs boolean as parameter and that’s why we have to check for null.

In this case ‘false’ is marked with warning ‘Remove the unnecessary boolean literal :: Boolean literals should not be redundant (java:S1125)’.

Of course, I can write this the other way and I will but I don’t get it why I’m getting a warning.

//  other way #1 (that I'm going to use)
final Boolean cardEnabled = parseAndGet("card-enabled");
cardButton.setVisible( Boolean.TRUE.equals( cardEnabled ) );

// other way #2
Boolean cardEnabled = parseAndGet("card-enabled");
if (cardEnabled == null) {
	cardEnabled = Boolean.FALSE;
cardButton.setVisible( cardEnabled.booleanValue() );

Short answer: It wants you to simplify to cardEnabled != null && cardEnabled. If you’re using IntelliJ, it’ll also highlight this expression and provide a “Quick Fix Action”

In fact, SonarLint also provides a quick fix action, but it produces the invalid expression
!cardEnabled == null which should be fixed.

Long answer:

First of all, calling .booleanValue() is not necessary. Java will automatically unbox that for you.

Secondly, take a look at the rule description.

Noncompliant code example
booleanMethod() ? false : exp;
Compliant solution
!booleanMethod() && exp;


Oh stupid me! This makes sense:

cardEnabled != null && cardEnabled


Hello there,
@H.Lo I am glad you could find an answer to the problem.
@lbenedetto we have been working on improving the quick fix suggestion for this case, and the suggestions should improve in the next release of the Java analyzer.




This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.