S6885: False positives for Math.clamp

Sonar raises java:S6885 (Use builtin “Math.clamp” methods) for the following code:

int a;
long b, c;
...
a = (int) Math.max(a, Math.min(Integer.MAX_VALUE, b + c));

The purpose is to ensure that the result stays within int boundaries if the addition of b + c exceeds the range. I fail to see how this can be converted into a Math.clamp call.
In general I believe clamp can only be used as a replacement if a is used in the nested min call but not if only used in the max call.

Hi @sithmein,

If I am not mistaken, the check is correct. You can write the expression as:

a = Math.clamp(b+c, a, Integer.MAX_VALUE)

I hope it helps you.

Best,
Erwan

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