Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can assign integer value to char but can't assign integer variable to char

Tags:

java

char

int

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?

like image 491
Evan Avatar asked Oct 19 '14 01:10

Evan


People also ask

Can you assign an integer to a char?

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.

Can we assign number to char variable?

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.

Is it legal to assign an int to a char variable?

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).

What happens if we assign a character to an integer variable?

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.


1 Answers

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.

like image 185
Elliott Frisch Avatar answered Oct 20 '22 00:10

Elliott Frisch