Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Long x;
int y = (int) x;

Eclipse is marking this line with the error:

Can not cast Long to an int

like image 249
Alex Avatar asked Apr 27 '11 08:04

Alex


2 Answers

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)

like image 100
Sean Patrick Floyd Avatar answered Oct 21 '22 06:10

Sean Patrick Floyd


Long x is an object.

int y = x.intValue();
like image 24
Ishtar Avatar answered Oct 21 '22 04:10

Ishtar