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#
- Core Concepts
- Typical Usage Scenarios
- Code Examples
- Common Pitfalls
- Best Practices
- Conclusion
- FAQ
- 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 alongto anint. This method simply takes the lower 32 bits of thelongvalue and discards the upper 32 bits. - Using
Math.toIntExact: This is a safer way provided by the Java standard library. It checks if thelongvalue is within the range of anint. If it is, it returns theintvalue; otherwise, it throws anArithmeticException.
Typical Usage Scenarios#
- Legacy API Compatibility: Some older Java APIs might only accept
intvalues. If you have alongvalue that you know is within theintrange, 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
longvalues you are dealing with will always fit within theintrange, converting tointcan save memory. - Data Truncation: In some cases, you may intentionally want to discard the higher-order bits of a
longvalue. For example, if you are working with a hash function that returns alongbut 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
longvalue is outside the range of anint, 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 theArithmeticExceptionproperly, your program may crash unexpectedly.
Best Practices#
- Use
Math.toIntExactfor Safety: Whenever possible, useMath.toIntExactto convert alongto anint. This method ensures that thelongvalue is within theintrange 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 thelongvalue is within theintrange 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#
- The Java Language Specification, https://docs.oracle.com/javase/specs/jls/se17/html/jls - 5.html#jls - 5.1.3
- Java API Documentation, https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#toIntExact - long -