subtractExact
multiplyExact
decrementExact
incrementExact
Math 类的addExact() 方法返回两个参数的和,如果结果溢出 long 或 int 则抛出异常。
句法
public static int addExact (int x, int y)
public static long addExact (long x, long y)
参数
x=第一个值
y=第二个值
返回值
addExact() 方法返回参数的总和。
投掷
addExact() 方法抛出:
ArithmeticException- 如果结果溢出 int 或 long
示例 1:
public class JavaMathAddExactExample1 {
public static void main(String[] args) {
// returns the sum of the arguments.
int x = -23;
int y = 123;
System.out.println("Sum : " + Math.addExact(x, y));
}
}
输出:
Sum : 100
示例 2:
public class JavaMathAddExactExample2 {
public static void main(String[] args) {
int x = -109;
int y = 109;
System.out.println("Sum : " + Math.addExact(x, y));
}
}
输出:
Sum : 0
示例 3:
public class JavaMathAddExactExample3 {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
int y = Integer.MIN_VALUE;
System.out.println("Sum : ");
System.out.print(x + "+" + "(" + y + ") = ");
System.out.println(Math.addExact(x, y));
}
}
输出:
Sum :
2147483647+(-2147483648) = -1
示例 4:
public class JavaMathAddExactExample4 {
public static void main(String[] args) {
long x = 95444353546386l;
long y = Long.MAX_VALUE;
System.out.println(Math.addExact(x, y));
}
}
输出:
at java.base/java.lang.Math.addExact(Math.java:845)
at Solution14.JavaMathAddExactExample4.main(JavaMathAddExactExample4.java:7)