Expression always evaluates to the same valueΒΆ
ID: java/evaluation-to-constant
Kind: problem
Severity: warning
Precision: very-high
Tags:
- maintainability
- useless-code
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
Some expressions always evaluate to the same result, no matter what their subexpressions are:
x * 0always evaluates to0.x % 1always evaluates to0.x & 0always evaluates to0.x || truealways evaluates totrue.x && falsealways evaluates tofalse. Wheneverxis not constant, such an expression is often a mistake.
RecommendationΒΆ
If the expression is supposed to evaluate to the same result every time it is executed, consider replacing the entire expression with its result.
ExampleΒΆ
The following method tries to determine whether x is even by checking whether x % 1 == 0.
public boolean isEven(int x) {
return x % 1 == 0; //Does not work
}
However, x % 1 == 0 is always true when x is an integer. The correct check is x % 2 == 0.
public boolean isEven(int x) {
return x % 2 == 0; //Does work
}
ReferencesΒΆ
Java Language Specification: Multiplication Operator *, Remainder Operator %, Integer Bitwise Operators &, ^, and |, Conditional-And Operator && and Conditional-Or Operator ||.