public class CharAndIntTest {
public static void main(String[] args) {
char i=\'1\';
int ii=65;
i=ii;
}
}
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;