This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Conversion and Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Conversion and Casting" Watch "Conversion and Casting" New topic
Author

Conversion and Casting

Chris Bui
Greenhorn

Joined: Jul 03, 2001
Posts: 1
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

Joined: Jan 30, 2000
Posts: 3222
    
    5
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>

Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
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


Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Conversion and Casting
 
Similar Threads
Roundup #13 answer explanation not totally right
promotion
code...
S.o.p (byte) 0X81 >> 2
Please explain....!!!!