# please explain. char problem.

Pankaja Shinde
Ranch Hand
Posts: 87

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
Posts: 52
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
Posts: 11
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
Rancher
Posts: 42968
73
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.

sushil bhogale
Greenhorn
Posts: 8
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
Posts: 8
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...