I can implicitly conver int to long and long to Long. Why is it not possible to implicitly convert int to Long? Why can't Java do the implicit conversion on the last line of the example?
int i = 10; //OK
long primitiveLong = i; //OK
Long boxedLong = primitiveLong; //OK
boxedLong = i; //Type mismatch: cannot convert from int to Long
Java int can be converted to long in two simple ways:This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
Any integral numeric type is implicitly convertible to any floating-point numeric type. There are no implicit conversions to the byte and sbyte types. There are no implicit conversions from the double and decimal types. There are no implicit conversions between the decimal type and the float or double types.
Long
and Integer
are objects. Boxing/unboxing only works with primitives.
Doing Long boxedLong = i
is like Long boxedLong = new Integer(10)
, that's a no no !
Plus, remember that there is no inheritance between Long
and Integer
so even Integer i = new Long()
is not valid
Boxing only works with primitives. That's why.
Try this: Long.valueOf(int);
Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With