Java Data Type How to - Add/Multiply/Subtract two integers, checking for overflow








Question

We would like to know how to add/Multiply/Subtract two integers, checking for overflow.

Answer

//from w w w  .  ja  v a  2 s . co m
public class Main {
  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 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;
  }

  public static int subAndCheck(int x, int y) {
    long s = (long) x - (long) y;
    if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
      throw new ArithmeticException("overflow: subtract");
    }
    return (int) s;
  }
}