How to convert long to int safely in java? Math.toIntExact(long value

Math.toIntExact(long value) method, which converts a long to an int safely. This method will throw an ArithmeticException if the long value is outside of the range of int.

Here’s an example code snippet that demonstrates how to use Math.toIntExact(long value):

long longValue = 1234567890L;
int intValue;

try {
intValue = Math.toIntExact(longValue);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("The long value is too large to fit into an int.");
}

In the code above, we first attempt to convert the long value to an int using Math.toIntExact(). If the value is outside of the range of int, an ArithmeticException is thrown, which we catch and then throw an IllegalArgumentException to indicate that the value is too large.

Note that the Math.toIntExact() method was introduced in Java 8, so it may not be available in earlier versions of Java.

In Java 7 or earlier versions, you can safely convert a long to an int by using type casting. However, you need to be careful because if the long value is too large to fit into the range of the int type, the result will be truncated.

Here’s an example code snippet that demonstrates how to safely convert a long to an int in Java:

long longValue = 1234567890L;
int intValue;

if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
intValue = (int) longValue;
} else {
throw new IllegalArgumentException("The long value is too large to fit into an int.");
}

In the code above, we first check whether the long value is within the range of int. If it is, we then safely convert it to an int using type casting. If the long value is too large to fit into the range of int, we throw an IllegalArgumentException.

Note that the L suffix is used to indicate that the value is a long literal, and the Integer.MIN_VALUE and Integer.MAX_VALUE constants represent the minimum and maximum values that an int can hold, respectively.

Leave a comment

Design a site like this with WordPress.com
Get started