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; //addExact() with int parameters. //Throw an exception 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 is1When we add a and b,
2147483647 + 1 => 2147483648 // Outside the range of int type
Therefore, the addExact() method causes an integer overflow exception.