首页javaintegerJava Data Type - 如何加/乘/减两个整数,检查溢出

Java Data Type - 如何加/乘/减两个整数,检查溢出

我们想知道如何加/乘/减两个整数,检查溢出。
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;
  }
}