my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes alleged lost of precision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "alleged lost of precision" Watch "alleged lost of precision" New topic
Author

alleged lost of precision

Francisco A Guimaraes
Ranch Hand

Joined: Mar 20, 2002
Posts: 182
Hi everybody, look at this two pieces of code:
1.
char c = 10;
int i = c;
2.
byte b = 10;
char c = a;
why the first one comp�les fine and in the second javac complains about a "possible lost of precision"? isn�t char 16 bits and byte 8 bits long? shouldn�t this be a simple widening conversion?
Francisco
[ July 12, 2002: Message edited by: Francisco A Guimaraes ]

Francisco<br />SCJP<br />please use the [code][/code] tags when showing code.Click <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=ubb_code_page" target="_blank" rel="nofollow">here</a> to see an example.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
The difference is that a char is unsigned while a byte is signed. Therefore, a byte, which is only 8 bits, could contain the value -17. A char, on the other hand, can never contain such a value. Therefore, the compiler complains about the assignment.
They key to understanding narrowing and widening conversions is to understand the relationship of the ranges of the operand data types, not just the size of them.
This thread doesn't discuss your case exactly, but it's closely related and might find it useful. You can find it here.
Corey


SCJP Tipline, etc.
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Ok... I don't have my book in front of me ... but this is how I remember the Mughal book describing it:

Anyt conversions following those arrows is fine, but conversions not using the arrows (like byte to char or short to char and vice versa) require an explicit cast.


- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Francisco A Guimaraes
Ranch Hand

Joined: Mar 20, 2002
Posts: 182
Thanks Corey and Jessica. I forgot char is unsigned!
Francsico
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: alleged lost of precision