6
Long x;
int y = (int) x;

Eclipse is marking this line with the error:

Can not cast Long to an int

manlio
  • 18,345
  • 14
  • 76
  • 126
Alex
  • 32,506
  • 16
  • 106
  • 171
  • possible duplicate of [How to convert long to int?](http://stackoverflow.com/questions/4355303/how-to-convert-long-to-int) – Bobby Apr 27 '11 at 08:47
  • 4
    Nope, not a dupe. The other question is about converting a `long`, this one's about converting a `Long`. Big difference! – Sean Patrick Floyd Apr 27 '11 at 08:52
  • Note that Long and long are different. "Long" is the class that wraps a value of the primitive type "long". – blizpasta Apr 27 '11 at 08:53

4 Answers4

34

Use primitive long

long x = 23L;
int  y = (int) x;

You can't cast an Object (Long is an Object) to a primitive, the only exception being the corresponding primitive / wrapper type through auto (un) boxing

If you must convert a Long to an int, use Long.intValue():

Long x = 23L;
int  y = x.intValue();

But beware: you may be losing information! A Long / long has 64 bit and can hold much more data than an Integer / int (32 bit only)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
14

Long x is an object.

int y = x.intValue();
Ishtar
  • 11,542
  • 1
  • 25
  • 31
3
int y = (int) (long) x;

is working.

Alex
  • 32,506
  • 16
  • 106
  • 171
2
Long x1 = 123L;
long x2 = 123L;


int y1 = Math.toIntExact(x1);
int y2 = Math.toIntExact(x2);

This conversion will work with primitive as well as with non-primitive types as well.

Aditya Aggarwal
  • 610
  • 6
  • 7