当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Math.addExact()用法及代码示例


java.lang.Math.addExact() 返回其参数的总和。如果结果溢出 int 或 long,它将抛出异常。

用法

public static int addExact(int a, int b) 
public static long addExact(long a, long b)

参数

a = the first value
b = the second value

返回

It returns the sum of its argument.
  • 如果参数之一是 Integer.MAX_VALUE 或 Long.MAX_VALUE,它将抛出 ArithmeticException。

例子1

public class AddExactExample1
{
    public static void main(String[] args) 
    {
        int a = 469;
        int b = 737;
        // Input two positive value, Output addition of a and b
        System.out.println(Math.addExact(a, b));
    }
}

输出:

1206

例子2

public class AddExactExample2
{
    public static void main(String[] args) 
    {
        long a = 835;
        long b = -1573;
        // Input two values, Output addition of a and b 
        System.out.println(Math.addExact(a, b));
    }
}

输出:

-738

例子3

public class AddExactExample3
{
    public static void main(String[] args) 
    {
        int a = Integer.MAX_VALUE;
        int b = 785;
        // Input integer overflow, Output AirthmeticException 
        System.out.println(Math.addExact(a, b));
    }
}

输出:

Exception in thread "main" java.lang.ArithmeticException:integer overflow
	at java.lang.Math.addExact(Math.java:790)
	at AddExactExample3.main(AddExactExample3.java:8)

示例 4

public class AddExactExample4
{
    public static void main(String[] args) 
    {
        long a = 25;
        long b = Long.MAX_VALUE;
        // Input long overflow, Output AirthmeticException 
        System.out.println(Math.addExact(a, b));
    }
}

输出:

Exception in thread "main" java.lang.ArithmeticException:long overflow
	at java.lang.Math.addExact(Math.java:809)
	at AddExactExample4.main(AddExactExample4.java:8)






相关用法


注:本文由纯净天空筛选整理自 Java Math.addExact() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。