• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Conversion and Casting

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does anyone have an explanation as to why this work?
byte result = 1;
result *= 2;
isn't a cast like this required?
result = (byte)(result * 2)
 
Desperado
Posts: 3226
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Normally yes but in this case the compiler was smart enough to notice that there would be no possible loss of precision.
Try changing to
<code>
byte result = 255;
result *= 2;
</code>
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chris and Tony
There is an implicit cast included in all of the compound assignment operators ( +=, -=, *=, etc...). http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304
The example Tony gave
byte result = 255;
result *= 2;
wont compile, because your initially trying to put a value into a byte that is too large to begin with. However, this will compile:
byte result = 120;
result *= 2;
and it prints -16, this is because it looses precisoin on the implicit cast.
hope this clears it up
Dave
 
if you think brussel sprouts are yummy, you should try any other food. And this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic