Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is implicit conversion from int to Long not possible?

Tags:

java

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
like image 421
Michal Krasny Avatar asked Nov 14 '14 14:11

Michal Krasny


People also ask

Can int be converted 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.

What happens in implicit conversion?

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.

Can float be implicitly converted to int?

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.


2 Answers

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

like image 182
ortis Avatar answered Oct 06 '22 08:10

ortis


Boxing only works with primitives. That's why.

Try this: Long.valueOf(int);

Documentation

like image 41
Cacho Santa Avatar answered Oct 06 '22 08:10

Cacho Santa