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?
Because, char are data types which hold 1 byte (8 bits) of data. So in char you can store integer values that can be represented by eight bits. That is 0-255 in normal case.
To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit. Here, we have a char. char val; Now assign int value to it.
would still be perfectly legal. A value of any numeric type may be assigned to a variable of any (other) numeric type, and the value will be implicitly converted (which may involve a change of representation and/or a risk of overflow).
In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character.
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.
See also JLS. Chapter 5. Conversions and Promotions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With