Java safe conversion of long to int

In most cases this is really not needed, if possible please keep the long as a long and work with it as such, but if needed the following works

public static int longToInt(long value) {
    if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (value + " cannot be cast to int without changing its value.");
    }
    return (int) value;
}

The reason that theLong.intValue() is not suggested here is that intValue rounds the value to fit a int – it don’t say it can’t be done.