Java Math toIntExact() 使用方法及示例 long转int

Java Math toIntExact()方法从指定的long参数返回int值。

toIntExact()方法的语法为:

Math.toIntExact(long value)

注意:toIntExact()是静态方法。因此,我们可以使用Math类名来访问该方法。

示例1:Java Math.toIntExact()

toIntExact()参数

value - 将作为int返回的参数

toIntExact()返回值

从指定的long值返回int值

class Main {
          
   
  public static void main(String[] args) {
          
   

    //创建long变量
    long value1 = 52336L;
    long value2 = -445636L;

    //将long更改为int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);

    //打印int值
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}

在上面的示例中,我们使用了Math.toIntExact()方法从指定long变量中获取int值。

示例2:Math.toIntExact()引发异常

如果返回的int值不在int数据类型的范围内,则toIntExact()方法将引发异常。

class Main {
          
   
  public static void main(String[] args) {
          
   

    //创建一个long变量
    long value = 32147483648L;

    //将long转换为int
    int num = Math.toIntExact(value);
    System.out.println(num);
  }
}

在上面的示例中,long变量的值为32147483648。当我们将long变量转换为时int,结果值超出了int数据类型的范围。

因此,toIntExact()方法引发integer overflow异常。

经验分享 程序员 微信小程序 职场和发展