char c = 3; // this will compile, even 3 is an int value int a = 3; char d = a; // this won�t compile, even 3 is an int value we have explicitely convert a to char as, char d = (char) a; why ?
pankaj shinde
Srinivas Kumar
Ranch Hand
Joined: Jul 14, 2005
Posts: 52
posted
0
char is 16 bit unsigned primitive data type where as int is 32 bit signed primitive data type. char can be implicitly converted to an int but where as int cannot be implicitly converted to char because int range is higher than that of char. Explicit casting is needed if we want to assign int value to char.
Antonio Trapero
Greenhorn
Joined: Mar 24, 2007
Posts: 11
posted
0
Yes but ---> char c = 3 compiles, and int a =3; char c =a no.
I think this is cause 3 its a compile time constant, and compiler feels happly and implicity put the cast.
If you do final int i = 3; char c = i;
this compiles fine.
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35223
7
posted
0
Explicit casting is needed if the compiler doesn't know for sure that the assigned value will fit.
char c = 3 compiles
Here the compiler knows that "3" will fit into a char.
and int a =3; char c =a no.
The compiler is only so smart. It sees a general assignment of int to char, and wants to see a cast.
If you do final int i = 3; char c = i; this compiles fine.
Here, again, the compiler knows for sure that a 3 is assigned, which will fit.
char c = 3; or int i = 3; c = 1; These both cases are of "Implicit narrowing primitive conversion on assignments" and hence it worked. it to work rules are - 1. The source should be a constant expression either of byte, short, char or int. 2. Also the destination should either be byte, short, char or int. 3. Most important the value should be in range.
To make it work... final int i = 2; // final mentions here that its a constant source... c = i;
On the other hand follwing would not work int i1 = 10; final int i2 = i1; char c = i2; becase, at compile time i2 does not have any value.
Hope it works.
Antonio
sushil bhogale
Greenhorn
Joined: Mar 13, 2007
Posts: 8
posted
0
1. Sorry... it should be
char c = 3; or int i = 3; ==> this should be final int i = 3 c = 1;
2. In response, I have wrongly written Antonio's name from other thread...
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.