Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), abs() etc. The java.lang.Math class contains various methods for performing basic numeric operations Here, in the page we will discuss about the math toIntExact() Method in java.
Java Math toIntExact() Method :
The Math.toIntExact(long value) method is a static method in the java.lang.Math class that converts a long value to an int value. It does this by checking if the value of the long can be represented as an int without loss of precision, and if so, it returns the int value. If the long value is too large to be represented as an int, the method throws an ArithmeticException.
Syntax :
public static int toIntExact(long value)
Parameters :value - the long value
Throws Exception : ArithmeticException - if the argument overflows an int
public class Main {
public static void main(String[] args) {
try {
// Convert 100000L to int
long longValue = 100000L;
int intValue = Math.toIntExact(longValue);
System.out.println(intValue); // Outputs: 100000
// Convert 9999999999L to int
longValue = 9999999999L;
intValue = Math.toIntExact(longValue);
// This line will not be reached because an ArithmeticException will be thrown
} catch (ArithmeticException e) {
System.out.println("Cannot convert 9999999999L to int because it is too large");
}
// Convert -100000L to int
long longValue = -100000L;
int intValue = Math.toIntExact(longValue);
System.out.println(intValue); // Outputs: -100000
}
}
Output :
100000
Cannot convert 9999999999L to int because it is too large
-100000
Explanation :In this example, we are converting three different long values to int values using the Math.toIntExact method. The input values are 100000L, 9999999999L, and -100000L. The output values are 100000, an ArithmeticException, and -100000, respectively.
public class Main {
public static void main(String[] args) {
try {
// Convert 9999999999L to int
long longValue = 9999999999L;
int intValue = Math.toIntExact(longValue);
// This line will not be reached because an ArithmeticException will be thrown
} catch (ArithmeticException e) {
System.out.println("Cannot convert 9999999999L to int because it is too large");
}
}
}
Output :
Cannot convert 9999999999L to int because it is too large
Explanation :In this example, we are attempting to convert the long value 9999999999L to an int using the Math.toIntExact method. However, this value is too large to be represented as an int, so the method throws an ArithmeticException. The try-catch block catches the exception and prints a message to the console indicating that the conversion was not possible.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment