Last Updated: 

Java Convert Long to Int

In Java, long and int are both primitive data types used to represent integer values. However, they differ in their range and memory usage. A long data type is 64 - bit and can hold larger values, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. On the other hand, an int is 32 - bit, with a range from -2,147,483,648 to 2,147,483,647. There are scenarios where you might need to convert a long value to an int value. This blog post will delve into the core concepts, typical usage scenarios, common pitfalls, and best practices related to converting a long to an int in Java.

Table of Contents#

  1. Core Concepts
  2. Typical Usage Scenarios
  3. Code Examples
  4. Common Pitfalls
  5. Best Practices
  6. Conclusion
  7. FAQ
  8. References

Core Concepts#

The conversion of a long to an int in Java is a narrowing primitive conversion. Since an int has a smaller range than a long, not all long values can be accurately represented as an int. When performing a narrowing conversion, the Java compiler allows it explicitly because there is a risk of information loss.

In Java, you can perform this conversion in two ways:

  • Explicit Casting: You can use an explicit cast operator (int) to convert a long to an int. This method simply takes the lower 32 bits of the long value and discards the upper 32 bits.
  • Using Math.toIntExact: This is a safer way provided by the Java standard library. It checks if the long value is within the range of an int. If it is, it returns the int value; otherwise, it throws an ArithmeticException.

Typical Usage Scenarios#

  • Legacy API Compatibility: Some older Java APIs might only accept int values. If you have a long value that you know is within the int range, you may need to convert it to pass it to these APIs.
  • Memory Optimization: If you are working on a memory-constrained environment and you are sure that the long values you are dealing with will always fit within the int range, converting to int can save memory.
  • Data Truncation: In some cases, you may intentionally want to discard the higher-order bits of a long value. For example, if you are working with a hash function that returns a long but you only need the lower 32 bits.

Code Examples#

Explicit Casting#

public class LongToIntExplicitCast {
    public static void main(String[] args) {
        // Define a long value
        long longValue = 12345L;
        // Explicitly cast the long value to an int
        int intValue = (int) longValue;
        System.out.println("Long value: " + longValue);
        System.out.println("Converted int value: " + intValue);
    }
}

In this example, we first define a long value. Then we use an explicit cast to convert it to an int. Finally, we print both the original long value and the converted int value.

Using Math.toIntExact#

import java.lang.ArithmeticException;
 
public class LongToIntUsingMath {
    public static void main(String[] args) {
        try {
            // Define a long value within the int range
            long longValue = 12345L;
            // Use Math.toIntExact to convert the long to an int
            int intValue = Math.toIntExact(longValue);
            System.out.println("Long value: " + longValue);
            System.out.println("Converted int value: " + intValue);
        } catch (ArithmeticException e) {
            System.out.println("The long value is out of the int range: " + e.getMessage());
        }
    }
}

In this example, we use Math.toIntExact to convert the long value to an int. If the long value is within the int range, it will be converted successfully. Otherwise, an ArithmeticException will be thrown, which we catch and handle.

Common Pitfalls#

  • Data Loss: When using explicit casting, if the long value is outside the range of an int, the result will be incorrect due to data loss. For example:
public class DataLossExample {
    public static void main(String[] args) {
        long largeLongValue = 2147483648L;
        int intValue = (int) largeLongValue;
        System.out.println("Original long value: " + largeLongValue);
        System.out.println("Converted int value: " + intValue);
    }
}

In this example, the long value 2147483648L is outside the int range. When we perform an explicit cast, the result will be incorrect because the upper bits are discarded.

  • Not Handling Exceptions: When using Math.toIntExact, if you don't handle the ArithmeticException properly, your program may crash unexpectedly.

Best Practices#

  • Use Math.toIntExact for Safety: Whenever possible, use Math.toIntExact to convert a long to an int. This method ensures that the long value is within the int range and throws an exception if it is not, preventing silent data loss.
  • Check the Range Manually: If you can't use Math.toIntExact (e.g., in an older Java version), you can manually check if the long value is within the int range before performing an explicit cast.
public class ManualRangeCheck {
    public static int convertLongToInt(long value) {
        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("Long value is out of int range");
        }
        return (int) value;
    }
 
    public static void main(String[] args) {
        long longValue = 12345L;
        try {
            int intValue = convertLongToInt(longValue);
            System.out.println("Converted int value: " + intValue);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Conclusion#

Converting a long to an int in Java is a common operation, but it comes with risks due to the difference in their ranges. Understanding the core concepts, typical usage scenarios, common pitfalls, and best practices is crucial for performing this conversion safely and effectively. By using methods like Math.toIntExact and checking the range manually, you can avoid data loss and ensure the reliability of your Java programs.

FAQ#

Q: What happens if I try to convert a long value that is out of the int range using explicit casting? A: The result will be incorrect due to data loss. The explicit cast simply takes the lower 32 bits of the long value and discards the upper 32 bits.

Q: Why should I use Math.toIntExact instead of explicit casting? A: Math.toIntExact is a safer method. It checks if the long value is within the int range. If it is, it returns the int value; otherwise, it throws an ArithmeticException, preventing silent data loss.

Q: Can I use Math.toIntExact in all Java versions? A: Math.toIntExact was introduced in Java 8. If you are using an older Java version, you can't use this method directly. You may need to implement a manual range check.

References#