Skip to content
Advertisement

How can I cast a Long to an int in Java?

Long x;
int y = (int) x;

Eclipse is marking this line with the error:

Can not cast Long to an int

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement