Java Math addExact() 方法

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));
	}
}

输出:

 
 
Exception in thread "main" java.lang.ArithmeticException: long overflow
    at java.base/java.lang.Math.addExact(Math.java:845)
    at Solution14.JavaMathAddExactExample4.main(JavaMathAddExactExample4.java:7)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值