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

1

6

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?

Rill answered 17/12, 2012 at 13:14 Comment(8)
Good question. I wonder if that would cause some ambiguities. (+1)Herbivorous
Technically, Long foo = 4 can't be evaluated at compile time.Puerilism
You mix up conversion with autoboxing.Hysterectomy
@Bevor: can you explain what you mean by 'conversion'?Rill
I don't mind if you want to close this as a duplicate, but deleting a comment suggesting that this /isn't/ a duplicate? I was specifically looking for a justification of this behaviour, such as ambiguous cases that would be introduced as NPE mentions.Rill
@Rill I hope my comment was deleted automatically because it had link to possible duplicate. I vote to reopen it but it is probably too late to get more votes and more detailed answer.Radack
@Rill If it wasn't closed as duplicate, it would still be subject to closing under Not Constructive. StackOverflow is just not about questions that promote discussion instead of answering.Alveta
The JLS defines nine boxing conversions and "int to Long" is not among the list. "float to Double" like Double 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
G
5
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.

Gadid answered 17/12, 2012 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.