Add two integers, checking for overflow in Java
Description
The following code shows how to add two integers, checking for overflow.
Example
/*from w w w . j a va2 s . c o m*/
import java.io.File;
public class Main {
/**
* Add two integers, checking for overflow.
*
* @param x an addend
* @param y an addend
* @return the sum <code>x+y</code>
* @throws ArithmeticException if the result can not be represented as an
* int
* @since 1.1
*/
public static int addAndCheck(int x, int y) {
long s = (long)x + (long)y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int)s;
}
public static void main(String[] argv){
System.out.println(addAndCheck(Integer.MAX_VALUE, Integer.MAX_VALUE));
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »