• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Still confused at Boxing/Narrowing/Widening, etc

 
Jose Campana
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello colleagues !

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))

Best Regards, and good Luck,

Jose
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jose,

I think you're letting yourself confuse yourself by assuming it's the result of narrowing instead of autoboxing.

Try:


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.

Then try:


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 ]
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that point, Rob. It's always useful to state the caveats to avoid creating greater confusion!
 
Jose Campana
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, amazing...

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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic