'Assign values to char in java [duplicate]
I tried
int a = 100;
char c = a; //doesn't work
but
char c = 100; //does work
Does anybody know why?
Solution 1:[1]
Sentence
char a = 100;
will work, as every number in char stands for symbol in Unicode, from 0 to 65,536
For example
char a = 435;
System.out.println("Output: " + a);
gives output
Output: ?
As mentioned in answer below, type cast needed, when assigning int value to char, as int has wider values range (from -2147483648 to 2147483647) than char
For example,
long a = 1;
int b = a;
also impossible
Solution 2:[2]
The reason why char c = a; does not work is since char and int are incompatible types.
char can store 2 bytes where as int can store 4 bytes. And so the java compiler does not allow the above operation since it can probably result in data loss while type conversion takes place.
To avoid the above issue, we can simply typecast int to char before assigning char c = (char) a;.
Solution 3:[3]
compiler won't do 'Widening or Automatic Type Conversion' for int to char. Reference
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Karthik C |
| Solution 3 | Ashutosh |
