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?
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?
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.
© 2022 - 2024 — McMap. All rights reserved.
Long foo = 4
can't be evaluated at compile time. – PuerilismDouble d = 1.5f
won't work either. An automatic widening+boxing is simply not specified. It's by far easier to ask the programmer to cast then to specify all possible widening/narrowing+boxing/unboxing cases. – Necrophilia