Why does primitive conversion involving "char" always require explicit cast?
Thomas Markl
Ranch Hand
Joined: Mar 08, 2001
Posts: 192
posted
0
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 :
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
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
The general rules for primitive assignment conversion can be stated as follows:
A boolean may not be converted to any other type
a non-boolean may be converted to another non-boolean type provided the conversion is a widening conversion.
A non-boolean may not be converted to another non-boolean type if the conversion would be a narrowing conversion.
Diagram of widening conversions:
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
It seems that all conversions involving a number and char reqire explicit cast.
A long is too big to fit into a char.
Conversions assigning a number variable to a char require an explicit cast. However, you can assign the int literal '45' to a char.
Ron Newman
Ranch Hand
Joined: Jun 06, 2002
Posts: 1056
posted
0
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)
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
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 ]
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.