Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
The following excerpt is from theSun's IntroductionSecure sectionCoding ofGuidelines Sun'sdocument \[[SCG 07|AA. Java References#SCG 07]\]:

...

While this statement is true, arithmetic operations in the Java platform require the same as much caution as in C and C++. Integer operations can result in overflow because Java does not provide any indication of these overflow conditions and silently wraps (Java arithmetic throws an exception only on a division by zero).

Wiki Markup
The following excerpt is from the Java Language Specification \[[JLS 03|AA. Java References#JLS 03]\] 4.2.2 Integer (Overflow)Operations:

The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a NullPointerException if unboxing conversion of a null reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator / and the integer remainder operator %, which throw an ArithmeticException if the right-hand operand is zero, and the increment and decrement operators ++ and -- which can throw an OutOfMemoryError if boxing conversion is required and there is not sufficient memory available to perform the conversion.

Noncompliant Code Example

In this noncompliant code example, the result can overflow.

Code Block
bgColor#FFcccc

public int do_operation(int a, int b)
{
   int temp = a + b;
   //Could result in overflow
   //perform other processing
   return temp;
}

If the result of the addition is greater than the maximum value or less than the minimum value that the int type can store, then the variable temp will contain an erroneous result. Although unlike C/C++ integer overflows are difficult to exploit due to the memory properties of the Java platform (e.g., explicit array bounds checking, if temp has a negative value as a result of an overflow and it is used as an array index, we get a java.lang.ArrayIndexOutOfBoundsException), the issue can lead to undefined or incorrect behavior.

All of the following operators can lead to overflows:

The table shown below enlists the operators that can lead to overflows:

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

+

yes

 

-=

yes

 

<<

no

 

<

no

-

yes

 

*=

yes

 

>>

no

 

>

no

*

yes

 

/=

yes

 

&

no

 

>=

no

/

yes

 

%=

no

 

\

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

+

yes

 

-=

yes

 

<<

no

 

<=

no

- %

yes no

 

*<<=

yes no

 

>> ^

no

  >

==

no *

++

yes

 

/>>=

yes no

 

& ~

no

 

>!=

no /

--

yes

 

%&=

no

 

| !

no

  <

= &&

no

% =

no

 

<<|=

no

  ^

un +

no

  =

= ||

no

++ =

yes

 

>>^=

no

 

~

no

 

!=

no

-un -

yes

  &

= ?:

no

 

!

no

 

&&

no

=

no

 

|=

no

 

un +

no

 

||

no

+=

yes

 

^=

no

 

un -

yes

 

?:

no

Addition

Addition (as with all arithmetic operations) in Java is performed on signed numbers only as unsigned numbers are unsupported.

Noncompliant Code Example

In this example, the addition operation can result in an overflow.

...

bgColor#FFcccc

Addition

Addition (as with all arithmetic operations) in Java is performed on signed numbers only as unsigned numbers are unsupported.

Noncompliant Code Example

In this noncompliant code example, the result of the addition can overflow.

Code Block
bgColor#FFcccc

public int do_operation(int a, int b){
  // May result in overflow 
  int temp = a + b;
  return temp;
}

If the result of the addition is greater than the maximum value or less than the minimum value that the int type can store, then the variable temp will contain an erroneous result. Unlike C and C++ integer overflows are harder to exploit in Java. For example, if temp has a negative value as a result of an overflow and is used as an array index, java.lang.ArrayIndexOutOfBoundsException) results whereas this is a more pernicious issue in C and C++ wherein memory regions outside the array bounds can be maliciously altered. In Java, wrapped values typically result in incorrect computations and unanticipated outcomes.

...

Compliant Solution (Bounds Checking)

Explicitly check the range of each arithmetic operation and throw an ArithmeticException on overflow; or else downcast the value to an integer. For performing arithmetic operations on large numbers, the BigInteger Class must be used.

Wiki Markup
According to the Java Tutorials \[[Tutorials 08|AA. Java References#Tutorials 08]\], Primitive Data Types:

_ _ -the integer data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
_ _ - the long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

Since the long type is guaranteed to hold the result of an int addition, we can assign the result to a long, and if the result is in the integer range, we can simply downcast. All the overflow condition checks would be the same as those used with signed integers in C.

...

the result to a long, and if the result is in the integer range, we can simply downcast to an int.

Compliant Solution (Use Long and Downcast)

This compliant solution uses the long type to store the result of the addition and proceeds to range check the value. If the value cannot be represented safely as an int, it throws an ArithmeticException. Otherwise, it downcasts the result to an int.

Code Block
bgColor#ccccff
public int do_operation(int a, int b) throws ArithmeticException
 {
   long temp = (long)a + (long)b;
   if(temp >Integer.MAX_VALUE || temp < Integer.MIN_VALUE)
     throw new ArithmeticException();
   else // Value within range can perform the addition
   //Do stuff
   return (int)temp;
}

Compliant Solution (Bounds Checking)

This is yet another example of explicit range checkingcompliant solution ensures that a and b variables are always positive and uses range checking to ensure that the result can be safely represented as an int.

Code Block
bgColor#ccccff
public int do_operation(int a, int b) throws ArithmeticException
{
        throws ArithmeticException {
  int temp;
       if(a>0 && b>0 && (a >Integer.MAX_VALUE - b) ||
       a<0 && b<0 && (a < Integer.MIN_VALUE -b))
         throw new    throw ArithmeticException();
       else
             temp = a + b;  //Value within range can perform the addition
      //Do stuff return
       temp;
}

Compliant Solution (Use BigInteger Class)

Another compliant approach would be to use This compliant solution uses the BigInteger class as a wrapper to test for the overflow.

Code Block
bgColor#ccccff
public boolean overflow(int a, int b)
 {
    java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
    java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
    java.math.BigInteger br = ba.add(bb);
    if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
              || br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1)
        return true;// Overflow!
    //Can proceed Else no overflow or underflow
   return false;
}

public int do_operation(int a, int b) throws ArithmeticException
 {
      if(overflow(a,b))
    throw     thrownew ArithmeticException();
  else 
   else // We are withinWithin range; safely perform the addition
}

With use of the BigInteger class, integer overflows are definitely eliminated. However, due to increased performance costs, it should be used only on large operations or when limited memory is not a concern.

Subtraction

Care must be taken while performing the subtraction operation as well since overflows are still possible.

Noncompliant Code Example

concern.

Subtraction

Care must be taken while performing the subtraction operation as well since overflows (or underflows) are still possible.

Noncompliant Code Example

In this noncompliant code example, the subtraction operation may underflow when a is a negative integer and b is a large positive integer such that their sum is not representable as an int. It can even overflow when a is positive whereas b is negative and their sum is not representable as an int.

Code Block
bgColor#FFcccc
public int do_operation(int a, int b)
 {
  int temp = a - b;
  // Could result in overflow
  // Perform other processing
  return temp;
}

Compliant Solution (Use Long)

The appropriate remediation is to check the range explicitly before This compliant solution suggests explicit range checking before performing the subtraction.

Code Block
bgColor#ccccff
public int do_operation(int a,b,result;

int b) {
  long temp = (long)a - (long)b;
  if(temp < Integer.MIN_VALUE || temp > Integer.MAX_VALUE)
    throw new ArithmeticException();
else

  else
    result = (int) temp;
  return temp;
}

Compliant Code Example (Use BigInteger Class)

A BigInteger class can be used as a test-wrapper as shown in this compliant solution.

Code Block
bgColor#ccccff
public boolean underflow(int a, int b)
 {
    java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
    java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
    java.math.BigInteger br = ba.subtract(bb);
    if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
            1
   || br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE)) == -1)
        return true;//We haveUnderflow
 underflow
 // No underflow //Canor proceedoverflow
   return false;
}

public int do_operation(int a, int b) throws ArithmeticException
 {
      if(undeflowunderflow(a,b))
    throw     thrownew ArithmeticException();
  else 
   else //we are withinWithin range; safely perform the additionsubtraction
}

Multiplication

This noncompliant code example can result in a signed integer overflow during the multiplication of the signed operands a and b. If this behavior is unanticipated, the resulting value may lead to undefined behavior.

Noncompliant Code Example

Code Block
bgColor#FFcccc
int a,b,result
//do stuff
result = a*b; // May result in overflow

Compliant Solution

...

Code Block
bgColor#ccccff
int a,b,result;
long temp = (long) a\* (long)b;
if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE)
  throw new ArithmeticException(); //overflow Overflow
else
  result = (int) temp; // Value within range, safe to downcast

Division

Although Java throws a java.lang.ArithmeticException for division by zero, the same issue as with C/C++ manifests, while dividing the Integer.MIN_VALUE by -1. It produces Integer.MIN_VALUE unexpectedly (since the result is -(Integer.MIN_VALUE) = Integer.MAX_VALUE + 1)).

Noncompliant Code Example

This noncompliant code example divides a and b without checking the range of the result.

Code Block
bgColor#FFcccc
int a,b,result
result = a/b;

...

 a,b,result
result = a/b;

Compliant Solution

This compliant solution handles the the special case of Integer.MIN_VALUE and -1 being used as the dividend and divisor, respectively.

Code Block
bgColor#ccccff
if(a == Integer.MIN_VALUE && b == -1)
  throw new ArithmeticException(); // May be Integer.MIN_VALUE againand -1
else
  result = a/b; //safe Safe operation

Remainder Operator

...

  • The sign of the remainder is always the same as that of the dividend. For example, -3 % -2 will result in the value -1. As a result its behavior can sometimes be deceptive -1. As a result its behavior can sometimes be deceptive.

Refer to INT02-J. Do not assume a positive remainder when using the % operator for more details.

Unary Negation

If we negate Integer.MIN_VALUE, we get is negated, the same value Integer.MIN_VALUE is obtained. Range checking is important in this case as well.

Noncompliant Code Example

This noncompliant code example tries to negate the result without checking whether it is Integer.MIN_VALUE. So we explicitly check the range.

Noncompliant Code Example

Code Block
bgColor#FFcccc
int temp = -result;

Compliant Solution

This compliant solution explicitly checks whether the input is Integer.MIN_VALUE and throws an exception if it is; otherwise, it negates the result.

Code Block
bgColor#ccccff
if(aresult == Integer.MIN_VALUE)
  throw new ArithmeticException();
else
  resulttemp = -aresult;

Absolute Value

A related pitfall is the use of the Math.abs() method that takes an integer as a int parameter and returns its absolute value. Due to Because of the asymmetry between the representation of negative and positive integer values (there is an extra minimum negative valuevalue -128), there is no equivalent positive value (+128) for Integer.MIN_VALUE. As a result, Math.abs(Integer.MIN_VALUE) always returns a non positive Integer.MIN_VALUE.

...

  • In C/C++ if the value being left shifted is negative or the right-hand operator of the shift operation is negative or greater than or equal to the width of the promoted left operand, we have there is undefined behavior. This does not extend to Java as integer types are masked by the last 5 lower order bits of the right operand (or 0x1F). This results in a value modulo 31, inclusive.
  • Wiki Markup
    When the value to be shifted (left-operand) is a {{long}}, only the last 6 bits of the right-hand operand are used to perform the shift. The shift distance is the value of the right-hand operand masked by 63 (0x3D)\[[JLS 03|AA. Java References#JLS 03]\], i.e., it is always between 0 and 63. (If the shift value is greater than 64, then the shift is {{value % 64}})

Refer to INT36-J. Use shift operators correctly for further details about the behavior of the shift operators.

Noncompliant Code Example

Wiki Markup
In this example, the programmer wishes to shift the integer {{i}} until, after 32 iterations, the value becomes 0. Unfortunately, this loop never terminates as an attempt to shift an integer{{int}} value by 32 bits results in the integer itself original {{int}} value rather than the value 0. \[[Bloch 05|AA. Java References#Bloch 05]\] 

...

Compliant Solution

This compliant solution shows how instead of repeatedly shifting shifts the value -1 with a different shift distance , one can save by saving the result of the previous shift and continue shifting continuing to shift it bit by bit on each successive iteration.

...