public class CharAndIntTest {
public static void main(String[] args) {
char i=\'1\';
int ii=65;
i=ii;
}
}
A char is a 16-bit datatype while an int is a 32-bit datatype. Thus, some possible int values can't be represented with a char without dropping some data (truncation). The compiler creates an error message to warn you about the possible problems caused by accidental truncation.
You can still assign int values to char if you do the appropriate casting:
int i=500;
char c = (char)i;
You can even assign illegal char values like this, although the result will still be truncated:
int i = 65555;
char c = (char)i; //still compiles and doesn't cause an exception, but data is lost
i = c; //i's value is 19
An int has larger capacity than a char, so the conversion is not guaranteed to work. The possible range in the value of a char is 0 to 65535, but an int can be anywhere from -2147483648 to 2147483647.
However, there are other considerations other than raw storage size. char is an unsigned type (Java's only built-in unsigned type, actually), so even short and byte variables still need a conversion to char as they may be negative. short and char are both 16 bit, but since short is signed its range is different from that of char (range of short being from -32,768 to 32,767).
The most important thing to learn here is that Java only lets implicit conversions take place if it can be absolutely determined that the conversion will succeed. This applies to primitives, objects, generics, and pretty much everything.
You can force the conversion to happen using a cast:
char i='1';
int ii=65;
i=(char)ii; //explicit cast tells the compiler to force the int into a char
chars are 16-bit unsigned numbers, so they got a maximum of 65,635.
ints are 32-bit signed numbers,s o they got a maximum of 2,147,483,647.
So something is bound to go wrong if you sign an int to a char, for all values >= 65,635.
The assignment conversion (JLS, Section 5.2) allows a primitive widening conversion, but not a primitive narrowing conversion:
Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
So you must cast to perform a primitive narrowing conversion, unless
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
So assigning a literal will work:
char a = 65;