...
| Code Block |
|---|
|
public int do_operation(int a, int b) throws ArithmeticException {
int temp;
if( (b>0 && (a > Integer.MAX_VALUE - b)) || (a < Integer.MIN_VALUE -b) )
throw new ArithmeticException();
else
temp = a + b; //Value within range can perform the addition
//Do stuff return
temp;
}
|
Compliant Solution (Use BigInteger Class)
...
| Code Block |
|---|
|
public boolean overflow(long a, long b) {
BigInteger ba = new java.math.BigInteger(String.valueOf(a));
BigInteger bb = new java.math.BigInteger(String.valueOf(b));
BigInteger br = ba.add(bb);
return (br.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 ||
br.compareTo(BigInteger.valueOf(Long.MIN_VALUE))== -1);
}
public intlong do_operation(long a, long b) throws ArithmeticException {
if(overflow(a,b))
throw new ArithmeticException();
else
// Within range; safely perform the addition
return a + b;
}
|
With use of the BigInteger class, integer overflows are definitely eliminated. However, due to increased performance costs, it should be used only when other methods are not appropriate.
...
| Code Block |
|---|
|
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)
...
| Code Block |
|---|
|
public int do_operation(int a,int b) {
long temp = (long)a - (long)b;
if(temp < Integer.MIN_VALUE || temp > Integer.MAX_VALUE)
throw new ArithmeticException();
else
result = (int) temp;
return temp;
}
|
Compliant Solution (Bounds Checking)
...
| Code Block |
|---|
|
public int do_operation(int a, int b) throws ArithmeticException {
int temp;
if( (b>0 && (a < Integer.MIN_VALUE + b)) || (a > Integer.MAX_VALUE + b) )
throw new ArithmeticException();
else
temp = a - b; //Value within range can perform the addition
//Do stuff return
temp;
}
|
Compliant Code Example (Use BigInteger Class)
...
| Code Block |
|---|
|
public boolean underflow(long a, long b) {
BigInteger ba = new BigInteger(String.valueOf(a));
BigInteger bb = new BigInteger(String.valueOf(b));
BigInteger br = ba.subtract(bb);
return (br.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 ||
br.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) == -1);
}
public intlong do_operation(long a, long b) throws ArithmeticException {
if(underflow(a,b))
throw new ArithmeticException();
else
// Within range; safely perform the subtraction
return a - b;
}
|
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.
...