File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Conversion and Casting" Watch "Conversion and Casting" New topic

Conversion and Casting

Chris Bui

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

Joined: Jan 30, 2000
Posts: 3226
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
byte result = 255;
result *= 2;

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

I agree. Here's the link:
subject: Conversion and Casting
It's not a secret anymore!