0 votes
1 view
in Java by (4.1k points)

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;

}

1 Answer

0 votes
by (46.1k points)

You can check out this new method that has been added with Java 8 to do just what you asked for.

import static java.lang.Math.toIntExact;

long foo = 10L;

int bar = toIntExact(foo);

Will return an ArithmeticException in the event of an overflow.

check out: Math.toIntExact(long)

Some other overflow safe methods have been attached to Java 8. They end with exact.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...