Java Math toIntExact() 方法
定义和用法
toIntExact()
方法将 long
值转换为 int
,如果转换导致溢出,则抛出异常。这可以防止因溢出而产生错误的结果。
实例
将 long 类型的值转换为 int 类型:
System.out.println(Math.toIntExact(1500000L)); System.out.println(Math.toIntExact(-32L)); System.out.println(Math.toIntExact(-86345L)); System.out.println(Math.toIntExact(25L));
语法
public static int toIntExact(long x)
参数
参数 | 描述 |
---|---|
x | 必需。要取反的整数。 |
技术细节
返回: | 表示 long 整型内容的 int 值。 |
---|---|
抛出: | ArithmeticException - 如果转换导致溢出。 |
Java 版本: | 1.8+ |