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


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

    toIntExact()方法的语法为:

    Math.toIntExact(long value)
    
    • 1

    注意: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
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在上面的示例中,我们使用了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);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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

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

  • 相关阅读:
    img为空时不显示
    介绍CY5-azide叠氮化物作为一种荧光染料的特点
    MySQL MHA
    密码学系列之:PEM和PKCS7,PKCS8,PKCS12
    Linux网络编程-极简HTTP&UDP服务器
    51LA网站访问统计使用【图文教程】
    PostgreSQL 修改数据库用户的密码
    在Docker中安装redis
    信息检索与智能问答
    PyQT5 QMessageBox对话框设置
  • 原文地址:https://blog.csdn.net/qq_42981242/article/details/127458643