Multiply two integers, checking for overflow in Java
Description
The following code shows how to multiply two integers, checking for overflow.
Example
/*from w ww .j a va 2 s. c o m*/
import java.io.File;
public class Main {
public static int mulAndCheck(int x, int y) {
long m = ((long)x) * ((long)y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: mul");
}
return (int)m;
}
}
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »