Guava – IntMath.checkedAdd()方法及实例

Guava – IntMath.checkedAdd()方法及实例

checkedAdd(int a, int b)是Guava的IntMath类的一个方法,接受两个参数 a and b ,并返回它们的总和。

语法:

public static int checkedAdd(int a, int b)

参数: 该方法接受两个int值a和b并计算它们的总和。

返回值: 该方法返回传递给它的int值的总和,只要它不溢出。

异常情况: 方法checkedAdd(int a, int b)抛出了ArithmeticException,如果和,即(a – b)在有符号的int算术中溢出。

下面的例子说明了上述方法的实现。

例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);
        }
    }
}

输出:



参考资料 :

https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#checkedAdd-int-int-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程