Safely casting long to int in Java

In Java, you can safely cast a long value to an int by checking to see if the long value is within the range of the int data type. If the long value is too large to be stored in an int, you can use another data type (such as a long or a BigInteger) to store the value.

Here is an example of how you can safely cast a long value to an int in Java:

long longValue = 1234567890;

if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
    // long value is too large to be stored in an int
    // handle error or use another data type to store the value
} else {
    // safe to cast long to int
    int intValue = (int) longValue;
}

Alternatively, you can use the longValue() method of the Integer class to safely convert a long value to an int:

long longValue = 1234567890;
int intValue = Integer.longValue(longValue);

Keep in mind that this method will return the int value that is equivalent to the long value, which may not be the same as the original long value if the long value is too large to be stored in an int.