418

How can I convert a long to int in Java?

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Arthur
  • 4,285
  • 2
  • 15
  • 3
  • 5
    Possible duplicate of [Safely casting long to int in Java](http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java) – BuZZ-dEE Feb 24 '17 at 10:08
  • ``if ((lval <= Integer.MAX_VALUE) && (lval >= Integer.MIN_VALUE)) intValue = (int)lval;`` – NomadMaker Jan 14 '21 at 08:31

20 Answers20

500

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.

Community
  • 1
  • 1
Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • What is the precision of integers? o_O – khachik Dec 04 '10 at 19:16
  • 7
    Casting has different meanings for objects and for primitive types. (int) l doesn't try to treat a 64-bit integer as a 32-bit integer, it actually returns a different 32-bit integer with the same 32 lower order bits. With objects, you cast to a more specific child class, but with primitve types, a cast is not really a cast, but a conversion. – dspyz Dec 06 '10 at 18:09
  • Int x = (int)(((Long)Integer.MAX_INTEGER)+10); If a conversion doesn't detect in this case that x has an improper value then you don't have a solution. – raisercostin Feb 22 '13 at 13:54
  • 4
    Math.toIntExact() is a great method actually. It throws and exception if the value is too big to fit in an int. Thanks for the suggestion. – java-addict301 May 22 '19 at 15:49
215
Long x = 100L;
int y = x.intValue();

bunyaCloven
  • 313
  • 1
  • 4
  • 14
Laxman
  • 2,643
  • 2
  • 25
  • 32
  • What's the difference between this way and just simply casting the value? I think, that all what `intValue()` does here in the background is casting the value.. Right? – Tim Wißmann Jan 28 '18 at 17:49
  • 7
    Note the types. Its not a primitive `long` here. Its the reference type `Long` which cant directly cast to an primitive `int`. `int y = (int)x;` will throws an execption but `int y = (int)(long)x` will work. (The reason is autoboxing) – akop May 14 '18 at 08:48
71

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.

Irregardless
  • 109
  • 7
mndrix
  • 3,131
  • 1
  • 30
  • 23
  • So a proper conversion will be to detect if the conversion is safe and throw an exception otherwise. Fact stated by @Andrej Herich that suggested Guava library. – raisercostin Feb 22 '13 at 13:57
  • Starting from Java 8, you could simly use Math.toIntExact – Attila Apr 30 '21 at 07:45
67

Since Java 8 you can use: Math.toIntExact(long value)

See JavaDoc: Math.toIntExact

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;
}
PhoneixS
  • 10,574
  • 6
  • 57
  • 73
Kuchi
  • 4,204
  • 3
  • 29
  • 37
39

If using Guava library, there are methods Ints.checkedCast(long) and Ints.saturatedCast(long) for converting long to int.

Jon
  • 9,156
  • 9
  • 56
  • 73
Andrej Herich
  • 3,246
  • 27
  • 14
  • 4
    There is no need of using libraries – Grekz Jan 16 '13 at 19:29
  • 6
    @Grekz that's up to the OP. I would in this case. More dependency jars is better than more reinvented wheels unless you have an actual reason not to have more dependency jars. – djechlin Aug 19 '13 at 20:44
  • 1
    IMHO, this answer is much better than the accepted one, in that it never does something unexpected. – Mark Slater Dec 02 '14 at 11:07
  • 5
    Since my project already include that jar, it would be more benefit to use it than to write a new helper – Osify Jun 17 '15 at 03:50
30
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?

Theo
  • 131,503
  • 21
  • 160
  • 205
  • 7
    Interesting to know is that according to par 5.1.3 in http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#189955 (The Java Language Spec): Despite the fact that overflow, underflow, or other loss of information may occur, narrowing conversions among primitive types never result in a run-time exception (§11). – extraneon Dec 04 '10 at 19:21
28

You can use the Long wrapper instead of long primitive and call

Long.intValue()

Java7 intValue() docs

It rounds/truncate the long value accordingly to fit in an int.

Kerwin Sneijders
  • 750
  • 13
  • 33
eleonzx
  • 677
  • 10
  • 16
  • It may be a good idea to link to the current documentation, as well as expand on this - inevitably, there's going to be some degree of rounding when converting a long to an int. – Makoto Jun 27 '12 at 01:57
  • 3
    Looking at the Java 7 implementation of Long.intValue(), it's just casting. No under/overflow checking is implemented. So at least through Java 7, this option is equivalent to just: (int)someLong. – buzz3791 Oct 30 '13 at 15:42
  • why less upvotes ? I found this one of most valuable Answer – Anand Kadhi Apr 18 '17 at 05:49
12

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
Stefan Hendriks
  • 4,705
  • 5
  • 34
  • 43
5

If direct casting shows error you can do it like this:

Long id = 100;
int int_id = (int) (id % 100000);
Mohammad H
  • 785
  • 2
  • 10
  • 25
4

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).

A int, on the other hand, is signed 32 bits number, which means you can store number 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:

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Alexis Dufrenoy
  • 11,784
  • 12
  • 82
  • 124
  • 1
    The question was already answered at the time I saw it, but the subject of the limits of the conversion was not explained. Which I did then. If you think that's "bla bla bla", that only means you're some kind of genius who can go without that sort of thing, but for us, mere humans, an explanation can be useful. Thank you for your "input"... – Alexis Dufrenoy Jan 17 '17 at 08:52
  • 1
    The site has gone downhill if the actual innerworkings of answers to questions are not just left out of highly voted answers, but are actually frowned upon. Information like this is absolutely necessary for a programmer to learn the language they’re using. Anyone who would consider this answer “bla bla bla” just wants other people to do the heavy lifting and write the code, that they can then copy. – Kröw May 17 '23 at 00:16
3

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.

Emdadul Sawon
  • 5,730
  • 3
  • 45
  • 48
1

Manual typecasting can be done here:

long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
YrvCodes
  • 21
  • 3
  • 1
    Please do not answer with a comment/question. Understandably, your rep is too low to comment, but that still does not mean answers should be used to make comments as an alternative. It would be preferable if you deleted this. – Clijsters Jul 01 '20 at 19:02
0

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)
0
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.

Daniel Tam
  • 41
  • 9
0

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ryuik
  • 69
  • 4
0
// 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
  }
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
-2

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();

MANOJ G
  • 632
  • 7
  • 7
-4

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));
-5
Long l = 100;
int i = Math.round(l);
tobias_k
  • 81,265
  • 12
  • 120
  • 179
Kristijan Drača
  • 614
  • 4
  • 16
-8

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);

convert long to int

ABC123
  • 1,037
  • 2
  • 20
  • 44
tsaowe
  • 45
  • 1
  • 4