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


Java StrictMath toIntExact()用法及代碼示例


java.lang.StrictMath.toIntExact()是Java中的內置方法,用於返回long參數的值。如果結果溢出一個int,它將引發異常。對象創建不是強製性的,因為toIntExact(long num)是靜態的。

用法:

public static int toIntExact(long num)

參數:該方法接受一個long類型的參數num,其返回的是int值。


返回值:該方法以int形式返回參數。

異常:如果參數溢出一個int,則拋出ArithmeticException。

例子:

Input: num = 2727l
Output: 2727

Input: num = -86262l
Output: -86262

下麵的程序演示了java.lang.StrictMath.toIntExact()方法:

示例1:

// Java program to demonstrate working 
// of java.lang.StrictMath.toIntExact() method 
  
import java.lang.StrictMath; 
  
class Geeks { 
  
    // driver code 
    public static void main(String args[]) 
    { 
  
        // Get the long value 
        // whose IntExact value is needed 
        long num = 266526l; 
  
        // Get the IntExact value 
        // using toIntExact() method 
        int intvalue = StrictMath.toIntExact(num); 
  
        // Print the IntExact value 
        System.out.print("IntExact value of "
                         + num + " = " + intvalue); 
    } 
}
輸出:
IntExact value of 266526 = 266526

示例2:

// Java program to demonstrate working 
// of java.lang.StrictMath.toIntExact() method 
  
import java.lang.StrictMath; 
  
class Geeks { 
  
    // driver code 
    public static void main(String args[]) 
    { 
  
        // Get the long value 
        // whose IntExact value is needed 
        long num = -7226526l; 
  
        // Get the IntExact value 
        // using toIntExact() method 
        int intvalue = StrictMath.toIntExact(num); 
  
        // Print the IntExact value 
        System.out.print("IntExact value of "
                         + num + " = " + intvalue); 
    } 
}
輸出:
IntExact value of -7226526 = -7226526

示例3:演示ArithmeticException

// Java program to demonstrate working 
// of java.lang.StrictMath.toIntExact() method 
  
import java.lang.StrictMath; 
  
class Geeks { 
  
    // driver code 
    public static void main(String args[]) 
    { 
  
        try { 
            // Get the long value 
            // whose IntExact value is needed 
            long num = 654456645546l; 
  
            System.out.println("Trying to get "
                               + "IntExact value of: "
                               + num); 
  
            // Get the IntExact value 
            // using toIntExact() method 
            int intvalue = StrictMath.toIntExact(num); 
  
            // Print the IntExact value 
            System.out.print("IntExact value of "
                             + num + " = " + intvalue); 
        } 
        catch (Exception e) { 
            System.out.println("Exception throwm: " + e); 
        } 
    } 
}
輸出:
Trying to get IntExact value of: 654456645546
Exception throwm: java.lang.ArithmeticException: integer overflow


相關用法


注:本文由純淨天空篩選整理自ankita_chowrasia大神的英文原創作品 StrictMath toIntExact() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。