Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top