My Java text mentions the following as conditions that must hold for implicit narrowing conversions on assignment
the source is a constant expression of either byte,short,char or int the destination is either byte,short or char the value of the source is determined to be in the range of the destination at compile time
Then it goes on to say that no implicit narrowing conversions whatsoever are allowed on passing to method parameters.
My first question is - why only allow types narrower than long ? Why not allow (for example) a constant double value that is in range ?
My second question is - why not allow any narrowing at all for parameter passing ? My understanding is that parameters are really created only when methods are called at runtime, but if the rules above hold wouldn't it make sense to be consistent with the treatment of assignments as is the case in other operations ?
Originally posted by Dirk Schreckmann:
My second question is - why not allow any narrowing at all for parameter passing ? My understanding is that parameters are really created only when methods are called at runtime, but if the rules above hold wouldn't it make sense to be consistent with the treatment of assignments as is the case in other operations ?
I'd imagine that a few folks feel it's not appropriate for a compiler to do any automatic narrowing. If you want a float, make it a float by casting it.
I'd guess that it's entirely possible and conceivable to create a compiler that would allow automatic narrowing of larger data type values known at compile time, which are passed as arguments to a method. But, again, this would likely complicate the compiler implementation mildly, as well as slow it down a bit.
So, again, these aspects of the Java programming language and compiler are this way because that's just how the original language and compiler designers wanted it - probably because it was easier and faster to implement.
Ever Existing, Ever Conscious, Ever-new Bliss
...Method invocation conversions specifically do not include the implicit narrowing of integer constants which is part of assignment conversion. The designers of the Java programming language felt that including these implicit narrowing conversions would add additional complexity to the overloaded method matching resolution process...
Consider Paul's rocket mass heater. |