Reputation: 4575
How can I convert a long to int in Java?
Upvotes: 447
Views: 1017349
Reputation: 11
You should be able to directly narrowly typecast/cast up from the higher data type (the long) to the lower one (the int), which would look like:
long x = 101010101L;
//explicit type casting
int y=(int)x;
Note that there would be some issues with a loss of data due to the smaller range of values accepted by the int.
long l = 2147483648L;
//
// T
// And we are trying to store a value in i
// greater than its upper limit
int i = (int) l;
(prints as -2147483648)
This would not be an issue with your example value. You can do this because both types of data are primitive values; whereas, if you were converting a string to an integer you would not be able to do this due to the string contents including characters, which are not accepted values for integers.
You would also be able to engage in explicit type conversion, which is used when converting the value of one data type to another data type without the compiler being able to do so. This would look like
//returns argument as int
//will throw ArithmaticException if the result overflows the int
//aka it is out of the range of -2,147,483,648 to 2,147,483,647
int b=Math.toIntExact(x);
int c= x.IntValue();
Note how this throws an exception when the long is out of range to be stored as an int rather than engaging in wraparound behavior and counting up from the negative limit of int after exceeding the maximum value of int.
When choosing between type casting or type conversion, you should note that casting changes the type of the variable, while conversion changes the representation or format of the value. Casting converts between compatible data types, while conversion can convert incompatible data types as well. Casting can result in data loss or truncation with narrowing (as in your case), while conversion can involve the manipulation or changing of data without changing the data type.
You can also reference here for more information:
https://www.scaler.com/topics/java/type-casting-in-java/
Upvotes: 0
Reputation: 11966
In Java, a long is a signed 64 bits number, which means you can store numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 (inclusive).
An int, on the other hand, is signed 32 bits number, which means you can store numbers between -2,147,483,648 and 2,147,483,647 (inclusive).
So if your long is outside of the values permitted for an int, you will not get a valuable conversion.
Details about sizes of primitive Java types here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Upvotes: 4
Reputation: 1
// Java Program to convert long to int
class Main {
public static void main(String[] args) {
// create long variable
long value1 = 523386L;
long value2 = -4456368L;
// change long to int
int num1 = Math.toIntExact(value1);
int num2 = Math.toIntExact(value2);
// print the type
System.out.println("Converted type: "+ ((Object)num1).getClass().getName());
System.out.println("Converted type: "+ ((Object)num2).getClass().getName());
// print the int value
System.out.println(num1); // 52336
System.out.println(num2); // -445636
}
}
Upvotes: 0
Reputation: 79
I'm adding few key details.
Basically what Java does is truncate long
after 32 bits, so simple typecasting will do the trick:
long l=100000000000000000l;
System.out.println(Long.toString(l,2));
int t=(int)l;
System.out.println(Integer.toString(t,2));
Which outputs:
101100011010001010111100001011101100010100000000000000000
1011101100010100000000000000000
for l=1000000043634760000l
it outputs:
110111100000101101101011110111010000001110011001100101000000
-101111110001100110011011000000
If we convert this -101111110001100110011011000000
in proper two's compliment we will get the exact 32-bit signed truncated from the long
.
Upvotes: 0
Reputation: 41
long x;
int y;
y = (int) x
You can cast a long to int so long as the number is less than 2147483647 without an error.
Upvotes: 0
Reputation: 15
I Also Faced This Problem. To Solve This I have first converted my long to String then to int.
int i = Integer.parseInt(String.valueOf(long));
Upvotes: -5
Reputation: 4801
Shortest, most safe and easiest solution is:
long myValue=...;
int asInt = Long.valueOf(myValue).intValue();
Do note, the behavior of Long.valueOf
is as such:
Using this code:
System.out.println("Long max: " + Long.MAX_VALUE);
System.out.println("Int max: " + Integer.MAX_VALUE);
long maxIntValue = Integer.MAX_VALUE;
System.out.println("Long maxIntValue to int: " + Long.valueOf(maxIntValue).intValue());
long maxIntValuePlusOne = Integer.MAX_VALUE + 1;
System.out.println("Long maxIntValuePlusOne to int: " + Long.valueOf(maxIntValuePlusOne).intValue());
System.out.println("Long max to int: " + Long.valueOf(Long.MAX_VALUE).intValue());
Results into:
Long max: 9223372036854775807
Int max: 2147483647
Long max to int: -1
Long maxIntValue to int: 2147483647
Long maxIntValuePlusOne to int: -2147483648
Upvotes: 12
Reputation: 3198
For small values, casting is enough:
long l = 42;
int i = (int) l;
However, a long
can hold more information than an int
, so it's not possible to perfectly convert from long
to int
, in the general case. If the long
holds a number less than or equal to Integer.MAX_VALUE
you can convert it by casting without losing any information.
For example, the following sample code:
System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );
long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);
int y = (int) x;
System.out.println("int y=" + y);
produces the following output on my machine:
largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648
Notice the negative sign on y
. Because x
held a value one larger than Integer.MAX_VALUE
, int y
was unable to hold it. In this case, it wrapped around to the negative numbers.
If you wanted to handle this case yourself, you might do something like:
if ( x > (long)Integer.MAX_VALUE ) {
// x is too big to convert, throw an exception or something useful
}
else {
y = (int)x;
}
All of this assumes positive numbers. For negative numbers, use MIN_VALUE
instead of MAX_VALUE
.
Upvotes: 73
Reputation: 21
Manual typecasting can be done here:
long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);
Upvotes: 1
Reputation: 1
If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression You can use it like:
val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
Upvotes: 0
Reputation: 687
You can use the Long
wrapper instead of long
primitive and call
Long.intValue()
It rounds/truncate the long
value accordingly to fit in an int
.
Upvotes: 29
Reputation: 670
long x = 3120L; //take any long value int z = x.intValue(); //you can convert double to int also in the same way
if you needto covert directly then
longvalue.intvalue();
Upvotes: -2
Reputation: 40914
Updated, in Java 8:
Math.toIntExact(value);
Original Answer:
Simple type casting should do it:
long l = 100000;
int i = (int) l;
Note, however, that large numbers (usually larger than 2147483647
and smaller than -2147483648
) will lose some of the bits and would be represented incorrectly.
For instance, 2147483648
would be represented as -2147483648
.
Upvotes: 533
Reputation: 6077
In Java 8 I do in following way
long l = 100L;
int i = Math.toIntExact(l);
This method throws ArithmaticException
if long
value exceed range of int
. Thus I am safe from data loss.
Upvotes: 3
Reputation: 45
In Spring, there is a rigorous way to convert a long to int
not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.
Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
Upvotes: -8
Reputation: 805
If direct casting shows error you can do it like this:
Long id = 100;
int int_id = (int) (id % 100000);
Upvotes: 6
Reputation: 3266
If using Guava library, there are methods Ints.checkedCast(long)
and Ints.saturatedCast(long)
for converting long
to int
.
Upvotes: 39
Reputation: 4694
Since Java 8 you can use: Math.toIntExact(long value)
Returns the value of the long argument; throwing an exception if the value overflows an int.
Source code of Math.toIntExact
in JDK 8:
public static int toIntExact(long value) {
if ((int)value != value) {
throw new ArithmeticException("integer overflow");
}
return (int)value;
}
Upvotes: 68
Reputation: 132972
long x = 3;
int y = (int) x;
but that assumes that the long
can be represented as an int
, you do know the difference between the two?
Upvotes: 30