public static long safeMultiply ( long a , int b ) { switch ( b ) { case - 1 : if ( a == Long . MIN_VALUE ) { throw new ArithmeticException ( "Multiplication overflows a long: " + a + " * " + b ) ; } return - a ; case 0 : return 0L ; case 1 : return a ; } long total = a * b ; if ( total / b != a ) { throw new ArithmeticException ( "Multiplication overflows a long: " + a + " * " + b ) ; } return total ; }
Safely multiply a long by an int .