[Java:S4973] Exclude Boolean from rule to compare boxed types via equals()

A comparison like

Boolean b = …;
if ( b == Boolean.TRUE )

does make sense. There are three valid states of a Boolean variable: null, Boolean.TRUE and Boolean.FALSE. All three are comparable via == operator.

Using equals() is complete nonsense for Booleans. Either you rely on auto unboxing and compare a Boolean with a boolean or you use the == operator to compare pointers like above.

Boolean boxes should be excluded from rule S4973.

Hi Marvin,

Welcome to the community! Thanks for a nice catch. Your idea does make sense. There is also one case, when this comparison is tricky. Boolean type has public constructor(depreceted from 9th version) and there is a way to create a new object. This code will probably have a bug:

if(new Boolean(true) == new Boolean(true)) {
// do something here
}

I’d rather suggest not to exclude Booleans from this check but do not report issue if we are comparing with Boolean.TRUE, Boolean.FALSE or null. Does it make sense to you? We highly appreciate your feedback!

Kind regards,
Margarita

Hi Margarita,

thanks for your quick reply. Yes, your suggestion does make sense. Didn’t know about the public constructor. Uhh!

Thanks and regards,
Marvin

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