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.asin()用法及代碼示例
- Java Math.atan()用法及代碼示例
- Java Math.acos()用法及代碼示例
- Java Math.abs()用法及代碼示例
- Java Math.multiplyExact()用法及代碼示例
- Java Math.rint()用法及代碼示例
- Java Math.nextUp()用法及代碼示例
- Java Math.tan()用法及代碼示例
- Java Math.nextAfter()用法及代碼示例
- Java Math.exp()用法及代碼示例
- Java Math.tanh()用法及代碼示例
- Java Math.toDegrees()用法及代碼示例
- Java Math.getExponent()用法及代碼示例
- Java Math.toIntExact()用法及代碼示例
- Java Math.IEEEremainder()用法及代碼示例
- Java Math.sqrt()用法及代碼示例
- Java Math.incrementExact()用法及代碼示例
- Java Math.min()用法及代碼示例
- Java Math.log()用法及代碼示例
- Java Math.log1p()用法及代碼示例
注:本文由純淨天空篩選整理自 Java Math.addExact() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。