case 1:
char c='A'+'A';
System.out.println(c); // print question mark (?)
case 2:
char c1='A';
char c2='A'+c1; // Compile time error
System.out.println(c2);
In case1 I have logic When I am adding two char literals, the sum of ascii value is printing which is equivalent to ascii value of question mark. But in case2 why compile time error is showing that 'cannot convert from int to char'
if char+char=int then this rule must be apply for both cases.
In the first case two final chars are added and at compile time it is checked that the resulting int does not overflow a char.
In the second case one operand is not final, and the compiler refuses to do a sum. A bit dumb, but considering multithreading and other cases, maybe justifiable. At least an easily understood rule.
Doing
final char c1 = '0';
char c2 = '1' + c1; // 'a'
should compile.
(It goes without say, that one should never do something like '0'+'1'
.)
Addition or 2 or more variables which are of type int or lower than int results in the type int.
So what you are doing with char c2 = 'A' + c1;
is actually not giving you a char result. It is giving you int result which you are trying to implicitly type cast to byte, which gives you the compile time error.
Summary Char + Char = Int And Char cannot directly store Int.
Try and do this instead
char c2 = (char)('A' + c1);
Here you explicitly type cast the int value to char type Telling the compiler that you are ready to accept the Lossy Conversion that may happen
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