Unnecessary Math Call On Constants
ID |
java.unnecessary_math |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
efficiency |
Description
Reports calls to Math.abs(), Math.max(), Math.min(), Math.round(), Math.ceil(), and Math.floor() where all arguments are literal constants. The result is computable at compile time, so the method call is unnecessary overhead.
Rationale
When every argument to a Math method is a literal, the return value is a constant. The JIT compiler may or may not fold the call away. Replacing it with the pre-computed value is clearer and eliminates any doubt.
// Bad - result is always 42
int x = Math.abs(-42);
// Bad - result is always 20
int y = Math.max(10, 20);
Remediation
Replace the call with the computed constant.
// Good - direct constant
int x = 42;
int y = 20;