当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。