java intvalueexact_Java Math toIntExact() 使用方法及示例

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

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

toIntExact()方法的语法为:

Math.toIntExact(long value)

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

toIntExact()参数value - 将作为int返回的参数

toIntExact()返回值从指定的long值返回int值

示例1:Java Math.toIntExact()

示例

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异常。

推荐的教程

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值