📜  Java中的 StrictMath toIntExact() 方法及示例

📅  最后修改于: 2022-05-13 01:55:22.266000             🧑  作者: Mango

Java中的 StrictMath toIntExact() 方法及示例

Java.lang.StrictMath.toIntExact()是Java中的一个内置方法,用于返回long参数的值。如果结果溢出一个int它将抛出一个异常。对象创建不是强制性的,因为 toIntExact(long num) 是静态的。

句法:

public static int toIntExact(long num)

参数:该方法接受一个返回int值的long类型的参数num

返回值:该方法将参数作为 int 返回。

异常:如果参数溢出int ,则抛出ArithmeticException

例子:

Input: num = 2727l
Output: 2727

Input: num = -86262l
Output: -86262

下面的程序说明了Java.lang.StrictMath.toIntExact() 方法:

方案一:

// 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

方案二:

// 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