Close

Java - Math.toIntExact() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Method:

public static int toIntExact(long value)

Returns the value of the long argument; throwing an exception if the value overflows an int.

Parameters:
value - the long value
Returns:
the argument as an int
Throws:
java.lang.ArithmeticException,ArithmeticException - if the argument overflows an int
Since:
1.8


Examples


package com.logicbig.example.math;

public class ToIntExactExample {

public static void main(String... args) {
intExact(0);
intExact(253);
intExact(785);
intExact(02);
intExact(57);
intExact(Long.MAX_VALUE);
}

private static void intExact(long value) {
System.out.println("----------");
int i = (int) value;
System.out.printf("Without Math.toIntExact of %s = %s %n", value, i);

try {
int degree = Math.toIntExact(value);
System.out.printf("Math.toIntExact(%s)= %s %n", value, degree);
} catch (ArithmeticException e) {
System.out.println("error: " + e);
}
}
}

Output

----------
Without Math.toIntExact of 0 = 0
Math.toIntExact(0)= 0
----------
Without Math.toIntExact of 253 = 253
Math.toIntExact(253)= 253
----------
Without Math.toIntExact of 785 = 785
Math.toIntExact(785)= 785
----------
Without Math.toIntExact of 2 = 2
Math.toIntExact(2)= 2
----------
Without Math.toIntExact of 57 = 57
Math.toIntExact(57)= 57
----------
Without Math.toIntExact of 9223372036854775807 = -1
error: java.lang.ArithmeticException: integer overflow




See Also