Why doesn't the following code compile
int n = 5; char c = n;
but the following does compile
char c = 5;
Aren't I just assigning an integer value to char in both cases?
A char can be assigned to an int without a cast because that is a widening conversion. To do the reverse, an int to a char requires a cast because it is a narrowing conversion.
char
int
See also JLS. Chapter 5. Conversions and Promotions.
2.1m questions
2.1m answers
63 comments
56.7k users