Asked • 04/10/19

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; }

1 Expert Answer


Istvan S. answered • 04/17/19

Programming Tutor and Tech Interview Coach

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.