• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conversion and Casting

 
Chris Bui
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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)
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • 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>
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic