Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k 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 (46k 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
asked Aug 7, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...