Avoid nextDouble() to Generate Random Integer
ID |
java.random_int_via_nextdouble |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability |
Rationale
Using nextDouble() multiplied by a bound and cast to int to generate random integers is less precise and more error-prone than nextInt(bound). The floating-point multiplication can introduce subtle bias, and the truncation from (int) cast discards useful precision. Random.nextInt(bound) is specifically designed for this purpose, is faster, and produces a uniform distribution.
// Bad - imprecise and verbose
int i = (int)(random.nextDouble() * 100);
Remediation
Use Random.nextInt(bound) instead.
// Good - correct and efficient
int i = random.nextInt(100);