Expression always evaluates to the same value¶
ID: java/evaluation-to-constantKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctnessQuery 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 whetherx is even by checking whetherx%1==0.
publicbooleanisEven(intx){returnx%1==0;//Does not work}
However,x%1==0 is always true whenx is an integer. The correct check isx%2==0.
publicbooleanisEven(intx){returnx%2==0;//Does work}
References¶
Java Language Specification:Multiplication Operator *,Remainder Operator %,Integer Bitwise Operators &, ^, and |,Conditional-And Operator && andConditional-Or Operator ||.