English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Math Mathematical Methods
Java Math addExact()方法将指定的数字相加并返回它。
addExact()方法的语法为:
Math.addExact(num1, num2)
注意:addExact()是静态方法。因此,我们可以使用类名Math来访问该方法。
num1 / num2 - 要返回其总和的第一个和第二个值
注意:这两个值的数据类型应为int或long。
返回两个值的和
import java.lang.Math; class Main { public static void main(String[] args) { //创建int变量 int a = 24; int b = 33; // 带int参数的addExact() System.out.println(Math.addExact(a, b)); // 57 //创建long变量 long c = 12345678l; long d = 987654321l; //带long参数的addExact() System.out.println(Math.addExact(c, d)); // 999999999 } }
在上面的示例中,我们使用了Math.addExact() 带有int和long参数的方法来计算总和。
如果加法的结果负出数据类型,addExact()方法将发发异常。有论为这个结果应该在指定参数的数据类型范囸内。
import java.lang.Math; class Main { public static void main(String[] args) { //创建int参数。 //最大int值 int a = 2147483647; int b = 1; //引入int参数的addExact()。 //折出异常 System.out.println(Math.addExact(a, b)); } }
In the above example, the value of a is the maximum int value and the value of b is1. When we add a and b,
2147483647 + 1 => 2147483648 // Out of the range of int type
Therefore, the addExact() method causes an integer overflow exception.