GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Expression always evaluates to the same value — CodeQL query help documentation

Expression always evaluates to the same value¶

ID: java/evaluation-to-constant
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
Query suites:
   - java-code-quality.qls
   - 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 * 0 always evaluates to 0.

  • x % 1 always evaluates to 0.

  • x & 0 always evaluates to 0.

  • x || true always evaluates to true.

  • x && false always evaluates to false. Whenever x is 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 ||.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.