• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

alleged lost of precision

 
Francisco A Guimaraes
Ranch Hand
Posts: 182
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Francisco A Guimaraes
Ranch Hand
Posts: 182
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Corey and Jessica. I forgot char is unsigned!
Francsico
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic