當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Longs.checkedSubtract(long a, long b)用法及代碼示例


CheckedSubtract(long a,long b)是Guava LongMath類的一種方法,該方法接受兩個參數a和b並返回它們的差值。

用法:

public static long checkedSubtract(long a, long b)

參數:該方法接受兩個long值a和b並計算它們的差。


返回值:該方法返回傳遞給它的long值的差,前提是它不會溢出。

異常:如果差異(即-a-b)在有符號long算法中溢出,則checkedSubtract(long a,long b)方法將引發ArithmeticException。

以下示例說明了上述方法的實現:

範例1:

// Java code to show implementation of 
// checkedSubtract(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 checkedSubtract(long a, long b) 
        // method of Guava's LongMath class 
        long ans1 = LongMath.checkedSubtract(a1, b1); 
  
        System.out.println("Difference of " + a1 + " and "
                           + b1 + " is:" + ans1); 
  
        long a2 = 150; 
        long b2 = 667; 
  
        // Using checkedSubtract(long a, long b) 
        // method of Guava's LongMath class 
        long ans2 = LongMath.checkedSubtract(a2, b2); 
  
        System.out.println("Difference of " + a2 + " and "
                           + b2 + " is:" + ans2); 
    } 
}
輸出:
Difference of 25 and 36 is:-11
Difference of 150 and 667 is:-517

範例2:

// Java code to show implementation of 
// checkedSubtract(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 checkedSubtract(long a, long b) method 
            // of Guava's LongMath class 
            // This should throw "ArithmeticException" 
            // as the difference overflows in signed 
            // long arithmetic 
            long ans = LongMath.checkedSubtract(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.lang.ArithmeticException:overflow

參考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#checkedSubtract-long-long-



相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | Longs.checkedSubtract(long a, long b) method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。