373

How to convert a Long value into an Integer value in Java?

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
Srinivasan
  • 11,718
  • 30
  • 64
  • 92
  • 15
    first you need to check if you Long doesn't exceed Integer MaxValue. – Lukasz Apr 27 '11 at 12:26
  • 8
    Java 8: http://stackoverflow.com/a/36331461/2291056 – Kuchi Mar 31 '16 at 11:00
  • 1
    Possible duplicate of [How can I convert a long to int in Java?](https://stackoverflow.com/questions/4355303/how-can-i-convert-a-long-to-int-in-java) – Alex K Oct 16 '18 at 19:14

14 Answers14

596
Integer i = theLong != null ? theLong.intValue() : null;

or if you don't need to worry about null:

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).

Java 8 has a helper method that checks for overflow (you get an exception in that case):

Integer i = theLong == null ? null : Math.toIntExact(theLong);
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 5
    It's the best answer because it handles NULL values. – Viacheslav Dobromyslov Apr 06 '14 at 01:05
  • 4
    @ViacheslavDobromyslov the question was about Long values, not about null values. And personally I believe in rejecting null up front rather than using null in -> null out and thereby transporting null through my application. So one could also argue this is the worst answer :-) – Sean Patrick Floyd Jun 11 '15 at 15:46
  • 1
    Why would you cast twice when you can just call `intValue` instead ? Plus it is going to unbox to long, cast to int, and rebox to `Integer`, which does not seem very useful. I don't see the point on top of my head, do you have a good reason for this ? – Dici Jul 14 '16 at 00:09
  • I am getting the error: Cannot invoke intValue() on the primitive type long – Anand Jul 22 '16 at 08:29
  • Anand it is because you initialized your value using 'long' instead of using 'Long' (primitive versus wrapper class) – The Prophet Feb 13 '18 at 15:57
  • why are you using `(int) (long) theLong` and not just `(int) theLong` ?? – mrid Apr 21 '19 at 08:02
  • @mrid Because that does not compile: "Long cannot be converted to int" – Thilo Apr 22 '19 at 02:42
  • 1
    @Thilo oh, I get it. Basically you're converting `Long` to `long` first, and then to `int` – mrid Apr 22 '19 at 03:02
133

Here are three ways to do it:

Long l = 123L;
Integer correctButComplicated = Integer.valueOf(l.intValue());
Integer withBoxing = l.intValue();
Integer terrible = (int) (long) l;

All three versions generate almost identical byte code:

 0  ldc2_w <Long 123> [17]
 3  invokestatic java.lang.Long.valueOf(long) : java.lang.Long [19]
 6  astore_1 [l]
 // first
 7  aload_1 [l]
 8  invokevirtual java.lang.Long.intValue() : int [25]
11  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
14  astore_2 [correctButComplicated]
// second
15  aload_1 [l]
16  invokevirtual java.lang.Long.intValue() : int [25]
19  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
22  astore_3 [withBoxing]
// third
23  aload_1 [l]
// here's the difference:
24  invokevirtual java.lang.Long.longValue() : long [34]
27  l2i
28  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
31  astore 4 [terrible]
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 12
    Minor styliustic issue: You should probably use the upper-case suffix `123L` for readability. – Joey Jul 12 '12 at 12:48
  • Or you can use a good font... and here we go again... :D (just j/k, I also do that) – davidcesarino Mar 31 '13 at 22:22
  • @ViacheslavDobromyslov true. the question was about Long, not null – Sean Patrick Floyd Mar 10 '14 at 08:51
  • 2
    @SeanPatrickFloyd yep. Don't forget that Long variable value could be NULL sometimes. – Viacheslav Dobromyslov Mar 11 '14 at 13:29
  • So why is the 3rd option terrible? (For some reason, you name the Integer variable "terrible". Why? That's the option I'm using. – user64141 Jun 11 '15 at 14:02
  • 2
    @user64141 Type casting in Java is a complicated issue. Casting Objects is fine, because you are actually not changing anything, just looking at the same object in a different way. But in this case, you have a chain of meaningful casts, from Object to primitive and then, through the madness of autoboxing, to object again, even though the syntax suggests it's another primitive. To me, this is a misuse of both boxing and primitive conversion. Not everything that can be done should be done. – Sean Patrick Floyd Jun 12 '15 at 06:55
59

For non-null values:

Integer intValue = myLong.intValue();
amukhachov
  • 5,822
  • 1
  • 41
  • 60
20

If you care to check for overflows and have Guava handy, there is Ints.checkedCast():

int theInt = Ints.checkedCast(theLong);

The implementation is dead simple, and throws IllegalArgumentException on overflow:

public static int checkedCast(long value) {
  int result = (int) value;
  checkArgument(result == value, "Out of range: %s", value);
  return result;
}
Dom
  • 1,687
  • 6
  • 27
  • 37
Jacob Marble
  • 28,555
  • 22
  • 67
  • 78
12

If you are using Java 8 Do it as below

    import static java.lang.Math.toIntExact;

    public class DateFormatSampleCode {
        public static void main(String[] args) {
            long longValue = 1223321L;
            int longTointValue = toIntExact(longValue);
            System.out.println(longTointValue);

        }
}
Dushyant Sapra
  • 585
  • 1
  • 8
  • 16
10

In Java 8 you can use Math.toIntExact. If you want to handle null values, use:

Integer intVal = longVal == null ? null : Math.toIntExact(longVal);

Good thing about this method is that it throws an ArithmeticException if the argument (long) overflows an int.

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
  • why not we use the above statement as below : Integer intVal = longVal != null ? Math.toIntExact(longVal) : null; A usual practice – ABHIJITH KINI Jul 27 '20 at 18:47
9

You'll need to type cast it.

long i = 100L;
int k = (int) i;

Bear in mind that a long has a bigger range than an int so you might lose data.

If you are talking about the boxed types, then read the documentation.

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
4

The best simple way of doing so is:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }
Adi
  • 2,074
  • 22
  • 26
3

Assuming not null longVal

Integer intVal = ((Number)longVal).intValue();

It works for example y you get an Object that can be an Integer or a Long. I know that is ugly, but it happens...

Edwin Miguel
  • 409
  • 4
  • 11
2

Using toIntExact(long value) returns the value of the long argument, throwing an exception if the value overflows an int. it will work only API level 24 or above.

int id = Math.toIntExact(longId);
Anjal Saneen
  • 3,109
  • 23
  • 38
1

long visitors =1000;

int convVisitors =(int)visitors;

Bala
  • 391
  • 4
  • 6
0

try this:

Int i = Long.valueOf(L)// L: Long Value

  • Welcome to Stack Overflow! Please note you are answering a very old and already answered question. Here is a guide on [How to Answer](http://stackoverflow.com/help/how-to-answer). – help-info.de Aug 13 '20 at 09:58
0

In addition to @Thilo's accepted answer, Math.toIntExact works also great in Optional method chaining, despite it accepts only an int as an argument

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0
usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305
-3

In java ,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);
tsaowe
  • 45
  • 1
  • 4