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 — Result of multiplication cast to wider type — CodeQL query help documentation

Result of multiplication cast to wider type¶

ID: java/integer-multiplication-cast-to-long
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - types
   - external/cwe/cwe-190
   - external/cwe/cwe-192
   - external/cwe/cwe-197
   - external/cwe/cwe-681
Query suites:
   - java-code-quality.qls
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

An integer multiplication that is assigned to a variable of type long or returned from a method with return type long may cause unexpected arithmetic overflow.

Recommendation¶

Casting to type long before multiplying reduces the risk of arithmetic overflow.

Example¶

In the following example, the multiplication expression assigned to j causes overflow and results in the value -1651507200 instead of 4000000000000000000.

int i = 2000000000;
long j = i*i; // causes overflow

In the following example, the assignment to k correctly avoids overflow by casting one of the operands to type long.

int i = 2000000000;
long k = i*(long)i; // avoids overflow

References¶

  • J. Bloch and N. Gafter, Java Puzzlers: Traps, Pitfalls, and Corner Cases, Puzzle 3. Addison-Wesley, 2005.

  • Java Language Specification: Multiplication Operator.

  • SEI CERT Oracle Coding Standard for Java: NUM00-J. Detect or prevent integer overflow.

  • Common Weakness Enumeration: CWE-190.

  • Common Weakness Enumeration: CWE-192.

  • Common Weakness Enumeration: CWE-197.

  • Common Weakness Enumeration: CWE-681.

  • © 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.