This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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