Long x;
int y = (int) x;
Eclipse is marking this line with the error:
Can not cast Long to an int
Long x;
int y = (int) x;
Eclipse is marking this line with the error:
Can not cast Long to an int
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)
int y = (int) (long) x;
is working.
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.