CheckedAdd(int a,int b)是Guava IntMath類的方法,該方法接受兩個參數a和b並返回它們的總和。
用法:
public static int checkedAdd(int a, int b)
參數:該方法接受兩個int值a和b並計算它們的和。
返回值:該方法返回傳遞給它的int值的總和,前提是它不會溢出。
異常:如果總和即(a-b)在有符號的int算術中溢出,則checkedAdd(int a,int b)的方法將引發ArithmeticException。
以下示例說明了上述方法的實現:
範例1:
// Java code to show implementation of
// checkedAdd(int a, int b) method
// of Guava's IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int a1 = 25;
int b1 = 36;
// Using checkedAdd(int a, int b)
// method of Guava's IntMath class
int ans1 = IntMath.checkedAdd(a1, b1);
System.out.println("Sum of " + a1 + " and "
+ b1 + " is:" + ans1);
int a2 = 150;
int b2 = 667;
// Using checkedAdd(int a, int b)
// method of Guava's IntMath class
int ans2 = IntMath.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(int a, int b) method
// of Guava's IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findDiff(int a, int b)
{
try {
// Using checkedAdd(int a, int b) method
// of Guava's IntMath class
// This should throw "ArithmeticException"
// as the sum overflows in signed
// int arithmetic
int ans = IntMath.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[])
{
int a = Integer.MIN_VALUE;
int b = 452;
try {
// Function calling
findDiff(a, b);
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
相關用法
- Java Guava Doubles.min()用法及代碼示例
- Java Guava Doubles.contains()用法及代碼示例
- Java Guava Floats.contains()用法及代碼示例
- Java Guava Bytes.contains()用法及代碼示例
- Java Guava Longs.contains()用法及代碼示例
- Java Guava Shorts.min()用法及代碼示例
- Java Guava Longs.min()用法及代碼示例
- Java Guava Chars.min()用法及代碼示例
- Java Guava Floats.min()用法及代碼示例
- Java Guava Longs.max()用法及代碼示例
- Java Guava Doubles.max()用法及代碼示例
- Java Guava Chars.max()用法及代碼示例
- Java Guava Floats.max()用法及代碼示例
- Java Guava Booleans.contains()用法及代碼示例
- Java Guava Shorts.contains()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | IntMath.checkedAdd(int a, int b) method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。