int myInt= 18;
long myLong= 16000;
myLong = myInt;
Here we are assigning an int to a long variable. Everything went smoothly, in a larger range, a smaller one fits quietly and we do not lose anything except memory space.
By the way, when we declare a variable of type long and define its value, it is better to assign the letter l to it, this will come in handy when we work with numbers outside the int range.
long myVeryLong = 10000000000l;
Java long to int conversion
Now let's get back to the main task of this article — Java long to int conversion. The problem is that something bigger doesn't always fit into something smaller. So here we can't just put “smaller” into “bigger” automatically in Java. If we try to act as in the previous example, but vice versa:
//example without typecasting…nice trying!
public static void main(String[] args) {
int myInt= 18;
long myLong= 16000;
myInt = myLong;
}
Java compiler just won't let us do this and will throw an error. So for this operation, we need to use what is called typecasting. This process is called narrowing type conversion.
To narrow a variable, you need to explicitly specify the type to which you want to cast your value.
Here is an example where we are going to try to put one “small” long to int (that should fit in) and two “big” long numbers that are out of int range.
public class longToInt {
public static void main(String[] args) {
int myInt = 18;
long myLong = 16000;
long myVeryLong = 2147483648l;//l in the end means ‘long’
long myVeryLong = 10000000000l;
myInt = (int) myLong;
System.out.println(myInt);
myInt = (int) oneMoreLong;
System.out.println(myInt);
myInt = (int) myVeryLong;
System.out.println(myInt);
}
}
We have notified the compiler that we want to put the long value into an int variable and we are responsible for the consequences of this decision. The compiler, seeing an explicit indication of a narrower type, performs the conversion. As a result, we get the output:
Java 8 long to int conversion
In Java 8, the Math class has a new method that will convert long to int. Here it is:
Math.toIntExact(value);
The best thing about this method is that it controls the length of the converted number, and if the value is too large to fit into an int, it will throw an exception.
Let's see how this works in our example:
public class intToLong {
public static void main(String[] args) {
int myInt = 18;
long myLong = 16000;
long oneMoreLong = 2147483648l;
long myVeryLong = 10000000000l;
System.out.println(Math.toIntExact(myLong));
int y = Math.toIntExact(oneMoreLong);
System.out.println(oneMoreLong);
System.out.println(Math.toIntExact(myVeryLong));
}
}
The output is:
Using BigDecimal for Long to Int Conversion
The BigDecimal
class in Java provides a reliable way to handle large numbers and ensures precision during conversions. While it is typically used for arithmetic operations with floating-point numbers, it can also be employed to safely convert a long
to an int
.
Example:
import java.math.BigDecimal;
public class BigDecimalConversion {
public static void main(String[] args) {
long longValue = 9223372036854775807L;
BigDecimal bigDecimal = new BigDecimal(longValue);
// Convert to int
int intValue = bigDecimal.intValueExact();
System.out.println("Converted int value: " + intValue);
}
}
Note: The intValueExact()
method throws an ArithmeticException
if the long
value exceeds the range of an int
.
Using Guava's saturatedCast Method
Google’s Guava library offers the saturatedCast
method, which safely converts a long
to an int
. This method ensures that values outside the range of an int
are automatically adjusted to Integer.MAX_VALUE
or Integer.MIN_VALUE
, depending on the overflow direction.
Example:
import com.google.common.primitives.Ints;
public class GuavaConversion {
public static void main(String[] args) {
long longValue = 9223372036854775807L;
// Using Guava's saturatedCast
int intValue = Ints.saturatedCast(longValue);
System.out.println("Converted int value: " + intValue);
}
}
Tip: Guava is a powerful library that simplifies many Java programming tasks. Consider including it in your projects for enhanced functionality.
Understanding Wrapper Classes for Conversion
Java’s Wrapper Classes provide an object-oriented approach to handle primitive data types. The Long
and Integer
classes offer methods to facilitate conversions between long
and int
.
Key Features of Wrapper Classes:
- Provide utility methods for type conversion.
- Enable boxing and unboxing of primitive types.
- Offer methods like
intValue()
for straightforward conversions.
Using intValue() Method for Conversion
The intValue()
method of the Long
wrapper class converts a Long
object to an int
primitive. It is a simple and effective approach for safe conversions.
Example:
public class WrapperClassConversion {
public static void main(String[] args) {
Long longValue = 100000L;
// Convert to int using intValue()
int intValue = longValue.intValue();
System.out.println("Converted int value: " + intValue);
}
}
Caution: If the Long
value exceeds the range of an int
, the result will be truncated, potentially causing data loss.
GO TO FULL VERSION