Math Method on Compile-Time Constant
ID |
java.math_on_compile_time_constant |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency |
Description
Reports calls to java.lang.Math methods where all arguments are compile-time constant literals.
Rationale
Calling a Math method on values that are known at compile time wastes runtime resources. The result is always the same and can be precomputed and stored as a constant, avoiding unnecessary method invocations on every execution.
// Bad - result is always 1.2
double d = Math.abs(-1.2);
// Bad - result is always 2.0
double s = Math.sqrt(4.0);
Remediation
Replace the call with the precomputed constant value.
// Good - use the precomputed result
double d = 1.2;
// Good - use the precomputed result
double s = 2.0;