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.
Why does primitive conversion involving "char" always require explicit cast? When I do a conversion from byte->char and vice versa it always requires cast. If I had done this with byte->int and vice versa then only conversion "int to byte" would have reqired explicit cast (as narrowing primitive conversion): Conversion char to byte and vice versa
C:\Java\EigeneJavaProgramme>javac Question02d.java Question02d.java:6: possible loss of precision found : char required: byte byte i = j; //line 2 corrected :
A byte is not too long to fit in a char, but a byte is signed while a char is unsigned. If the value of your byte is between -128 and -1, it will be changed into some positive number. The compiler is trying to draw your attention to this fact -- by writing an explicit cast, you can tell the compiler that you're aware of it.
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Joined: May 05, 2000
Originally posted by Thomas Markl: Hello Paul, I tried out to convert long to char and vice versa. It seems that all conversions involving a number and char reqire explicit cast. Is it so? Ciao Thomas
Yes it is. Here is the chart: byte - short - int - long - float - double Any movement towards the right does not require a cast. Any movement towards the left requires a cast. Any movement to char (which isn't in the list) requires a cast. [ August 31, 2002: Message edited by: Thomas Paul ]