Explain Codes LogoExplain Codes Logo

How can I convert a long to int in Java?

java
data-types
conversion-strategies
safe-coding-practices
Nikita BarsukovbyNikita Barsukov·Sep 24, 2024
TLDR

In Java, casting serves as the simplest way to convert a long to an int:

int convertFromLong = (int) sourceLong;

Yet, be mindful of overflow issues, i.e., when sourceLong is beyond Integer.MAX_VALUE. Here's how you deal with that:

if (sourceLong >= Integer.MIN_VALUE && sourceLong <= Integer.MAX_VALUE) { int convertFromLong = (int) sourceLong; } else { throw new ArithmeticException("Oops! This value is too chubby for an int!"); }

As evident, casting manages the conversion, while checking for integrity via range assessment protects us from data loss.

However, for a safer conversion that checks for overflow, use Math.toIntExact(long):

int safeInt = Math.toIntExact(sourceLong);

This method will throw a fit — umm, an exception — for values out of int range, thus ensuring more reliability.

Taking care of precision and safety

During numeric conversions, precision and safety are paramount. Herein, we will discuss strategies to uphold these.

Using wrapper classes judiciously

The Long wrapper class presents a handy method to morph into int:

Long longNumber = someHugeNumberL; int smallerNumber = longNumber.intValue();

This method remains flexible and keeps quiet about any overflow — a trait termed silent conversion — much like casting.

Preventing data obesity with Guava library

If you have Guava handy:

  • Ints.checkedCast(long) guarantees safe conversion:
int safeValue = Ints.checkedCast(sourceLong);

Mimicking your fitness trainer, it throws an IllegalArgumentException should an overflow occur.

  • Ints.saturatedCast(long) acts like the bouncer at the integer club:
int dietingValue = Ints.saturatedCast(sourceLong);

Values too large for int to handle get reduced to Integer.MAX_VALUEor Integer.MIN_VALUE.

Understanding Java logic through the JDK

Probing the JDK's logic, such as in Math.toIntExact, unveils insights into Java internals and safe coding practices.

Strategies for managing larger-than-int values

Encountered long values that are laughing at int? Here's how you can grapple.

Pre-casting check

Perform an explicit check of long value against int range:

int verifyBeforeCasting(long longValue) { if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) { // Handle Overflow: Scream, run in circles or use a default value } return (int) longValue; }

Deploy these checks to ensure the conversion does not unleash a data-losing monster.

Pondering alternative data strategies

If accurate representation of huge values matters, consider alternatives. Large data types or custom data handling mechanisms might be helpful.

Validate post-conversion

After the conversion party, verify the int result still represents the original long value:

long celestialNumber = offTheChartsL; int humbleNumber = (int) celestialNumber; if ((long) humbleNumber != celestialNumber) { // Mismatch alert! Summon your error handling protocol. }

The taming of the long

Picturing the long to int conversion process, think of it as downsizing the wayward tadpole to a less troublesome entity.

The Coder's Pet (🦎) Size: LONG Desired Pet Size: INT

In essence, you are asking it to shrink:

🦎➡️🐠 (Frank the Lizard) => (Tina the Tetra)

Now coming to actual code:

long frankLizard = 3456789012L; int tinaFish = (int) frankLizard; // Frank is now the size of Tina but watch for memory loss!

Ensure to verify if your long pet can indeed fit into an int aquarium without any overflow!

Also, consider the performance trade-offs of different conversion techniques. Some methods may be slower than the time it takes for Frank to lose weight, affecting your code's efficiency.