Could I ask a question? I hope so... I thought it'd be nice If I asked politely...
Could you guys please explain to me (once more) Why is this allowed ?
I'm asking because I supposed that first, 10 was an int literal by default, and second, I assumed that given that it is an int literal, before boxing, it was necessary to narrow it down to a byte, so that, then it could be boxed into the Byte Object...
--That would be two-steps, and we know the compiler can't handle it. So, could you please teach me how the code I posted works ? (because it doesn't give any compiler errors (in Java 6.0))
I think you're letting yourself confuse yourself by assuming it's the result of narrowing instead of autoboxing.
A byte can be any value from -128 to 127, inclusive. So if the assigned value is in the valid range, you can assign it directly.
Which won't compile, because it's beyond the valid range.
If an int literal is assigned to a short or a byte, and its value is within legal range, the literal is assumed to be a short or a byte. [Edit: be sure to see Rob's followup point in the next response!] [ April 30, 2008: Message edited by: Stevi Deter ]
There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Be careful though, this only works with assignment. If you pass a literal like 10 to any method, that's always going to be treated as an int, even though it fits in the ranges of byte, short and char. If the method requires one of those three, you have to cast 10:
Thanks for that point, Rob. It's always useful to state the caveats to avoid creating greater confusion!
Joined: May 28, 2007
You know Stevi, that's where my confusion came from, and I didn't realize it until now. It is because literals are not allowed when passed to methods that I began to wonder why,.... I focused on the wrong issue though, because the complex questions about this subject always deal with a scenario that provides a lot of overloaded methods not assignments.
But I'm Happy now, because that little explanation is exactly the one I desperately needed.
Thank you Rob! Thank you Stevi! See you next time! Keep up the Amazing work! Sincerely, Jose