Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java support coercion and autoboxing? [duplicate]

Possible Duplicate:
Java: Long result = -1: cannot convert from int to long

For example Integer foo = 4 and Long foo = 4L both compile, but Long foo = 4 doesn't. Is there a rationale for this?

like image 714
hertzsprung Avatar asked Dec 17 '12 13:12

hertzsprung


1 Answers

Long foo = 4;

means: assign an int of value 4 to a object of class Long. It will try to use autoboxing to do so and fail, because autoboxing is only applicable for the appropriate primitive. It can be fixed in two ways:

Long foo = (long) 4;
Long foo = 4L;

in the first case you cast the int 4 to long 4. In the second, you provide a long.

To answer the question: Java doesn't support auto-casting and is very strict in typing, which is probably why it doesn't support it automatically.

like image 162
Bart Friederichs Avatar answered Sep 28 '22 04:09

Bart Friederichs