Search code examples
javacasting

Safely casting long to int in Java


What's the most idiomatic way in Java to verify that a cast from long to int does not lose any information?

This is my current implementation:

public static int safeLongToInt(long l) {
    int i = (int)l;
    if ((long)i != l) {
        throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
    }
    return i;
}

Solution

  • A method was added in Java 8:

    import static java.lang.Math.toIntExact;
    
    long foo = 10L;
    int bar = toIntExact(foo);
    

    Will throw an ArithmeticException in case of overflow.

    See: Math.toIntExact(long)

    Several other overflow safe methods have been added to Java 8. They end with exact.

    Examples:

    • Math.incrementExact(long)
    • Math.subtractExact(long, long)
    • Math.decrementExact(long)
    • Math.negateExact(long),
    • Math.subtractExact(int, int)