English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Math Mathematical Methods
The Java Math toIntExact() method returns an int value from the specified long parameter.
The syntax of the toIntExact() method is:
Math.toIntExact(long value)
Note: toIntExact() is a static method. Therefore, we can use the Math class name to access this method.
value - The parameter returned as int
Return int value from the specified long value
class Main { public static void main(String[] args) { //Create long variable long value1 = 52336L; long value2 = -445636L; //Change long to int int num1 = Math.toIntExact(value1); int num2 = Math.toIntExact(value2); //Print int value System.out.println(num1); // 52336 System.out.println(num2); // -445636 } }
In the above example, we used the Math.toIntExact() method to obtain an int value from the specified long variable.
If the returned int value is not within the range of the int data type, the toIntExact() method will throw an exception.
class Main { public static void main(String[] args) { //Create a long variable long value = 32147483648L; //Convert long to int int num = Math.toIntExact(value); System.out.println(num); } }
In the above example, the value of the long variable is32147483648When we convert a long variable to an int, the resulting value exceeds the range of the int data type.
Therefore, the toIntExact() method triggers an integer overflow exception.