[java:S2140] FP

Qube version: 25.7.0.110598 Community
Java: 21

The rule java:S2140 produces an FP when the random floating point number is multiplied with a long to produce another long.

private void foo()
{
    Random rnd = new SecureRandom();
    
    long l0 = 10L;
    long l = (long) ( rnd.nextDouble() * l0 ); // FP
    System.out.println( l );
}

The rule suggests to use nextLong() instead of nextDouble() with a case to long.

In this example the random double is multiplied by another long to compute a fraction of that long, which is then casted to a long.

I don’t see, how nextLong() could help here.

Hi Marvin,

This looks like a true positive to me - the code can be rewritten as follows:

Random rnd = new SecureRandom();

long l0 = 10L;
long l = rnd.nextLong(l0);
System.out.println(l);

Please let me know if there’s anything I missed.

1 Like

You’re absolutely right. Thanks for the heads up. And sorry for the false alarm.

1 Like

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