checkAdd(long a,long b)是Guava LongMath类的方法,该方法接受两个参数a和b并返回它们的总和。
用法:
public static long checkedAdd(long a, long b)
参数:该方法接受两个long值a和b并计算它们的总和。
返回值:该方法返回传递给它的long值的总和,前提是它不会溢出。
异常:如果总和即(a-b)在有符号的long算术中溢出,则checkedAdd(long a,long b)方法将引发ArithmeticException。
以下示例说明了上述方法的实现:
范例1:
// Java code to show implementation of
// checkedAdd(long a, long b) method
// of Guava's LongMath class
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
// Driver code
public static void main(String args[])
{
long a1 = 25;
long b1 = 36;
// Using checkedAdd(long a, long b)
// method of Guava's LongMath class
long ans1 = LongMath.checkedAdd(a1, b1);
System.out.println("Sum of " + a1 + " and "
+ b1 + " is:" + ans1);
long a2 = 150;
long b2 = 667;
// Using checkedAdd(long a, long b)
// method of Guava's LongMath class
long ans2 = LongMath.checkedAdd(a2, b2);
System.out.println("Sum of " + a2 + " and "
+ b2 + " is:" + ans2);
}
}
输出:
Sum of 25 and 36 is:61 Sum of 150 and 667 is:817
范例2:
// Java code to show implementation of
// checkedAdd(long a, long b) method
// of Guava's LongMath class
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
static long findDiff(long a, long b)
{
try {
// Using checkedAdd(long a, long b) method
// of Guava's LongMath class
// This should throw "ArithmeticException"
// as the sum overflows in signed
// long arithmetic
long ans = LongMath.checkedAdd(a, b);
// Return the answer
return ans;
}
catch (Exception e) {
System.out.println(e);
return -1;
}
}
// Driver code
public static void main(String args[])
{
long a = Long.MIN_VALUE;
long b = 452;
try {
// Function calling
findDiff(a, b);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
相关用法
- Java LongMath.divide(long, long, RoundingMode)用法及代码示例
- Java Longs.checkedSubtract(long a, long b)用法及代码示例
- Java Longs.indexOf(long[] array, long target)用法及代码示例
- Java Longs.indexOf(long[] array, long[] target)用法及代码示例
- Java LongMath.checkedPow(long b, int k)用法及代码示例
- Java LongMath log10(long x, RoundingMode mode)用法及代码示例
- Java Guava LongMath gcd(long a, long b)用法及代码示例
- Java Guava LongMath mod(long x, long m)用法及代码示例
- Java Guava LongMath mean(long x, long y)用法及代码示例
- Java Guava LongMath pow(long b, int k)用法及代码示例
- Java Guava LongMath isPowerOfTwo(long x)用法及代码示例
- Java Guava LongMath sqrt(long x, RoundingMode mode)用法及代码示例
- Java Duration ofSeconds(long, long)用法及代码示例
- Java Guava Shorts.contains()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | LongMath.checkedAdd(long a, long b) method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。