Explain Codes LogoExplain Codes Logo

Safely casting long to int in Java

java
overflow-control
safe-casting
java-8
Anton ShumikhinbyAnton Shumikhin·Sep 6, 2024
TLDR

If you need a quick solve, remember to cast a long to an int only within the range of Integer.MIN_VALUE to Integer.MAX_VALUE. Don't rush this, unless you enjoy data loss from overflow/underflow. Yes, you can lose data in software engineering - not just in Battleship.

long longValue = // your long value; if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) { int intValue = (int) longValue; // Safe like grandma's kitchen } else { // Run! It's Godzilla! (Also handle error) }

Streamlined safeguard: Math.toIntExact makes casting safer than a double-seater bike

Java 8 wears the hero cape with Math.toIntExact(), offering a safer way to cast:

long longValue = // it's a big world; try { int intValue = Math.toIntExact(longValue); // It's Miller Time! } catch (ArithmeticException e) { // Baby on board! Handle possible overflow. }

Math.toIntExact() saves you from surprise ArithmeticExceptions like those pop-up ads you despise.

Short detour: Overflow control with Java 8

Java 8 not only brings nifty traffic lights (read: methods) for overflow control but also coats the road with overflow proofing like incrementExact, subtractExact, decrementExact, negateExact, subtractExact. Go ahead, take the roadster out for a spin!

Overflow-safe casting with Google Guava

No Java 8? Don't sweat. Lie back and let Google Guava do the heavy lifting:

long longValue = // some hotshot long value; try { int intValue = Ints.checkedCast(longValue); // Let's Guava this. } catch (IllegalArgumentException e) { // Houston, we couldn't fit the long into int. Manage this. }

Embracing precision with BigDecimal

Sometimes you need casting precision, not compromises. BigDecimal is your smooth operator:

long longValue = // some long; int intValue = new BigDecimal(longValue).intValueExact(); // Highly precise, like a Swiss watch!

Java to the rescue: Safer casting methods

Feeling overwhelmed by this casting call? Java offers a safety net. Just like an overprotective mom, it ensures that you don't trip and hurt yourself.

long goodLong = 2L * Integer.MAX_VALUE; // Bigger than life! int badInt = (int) goodLong; // Uh-oh. Didn't see that one coming did you?

Choose safety over surprises. You're not playing Russian Roulette here.