Randhir
Randhir

Reputation: 314

add two char data type in java

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.

Upvotes: 6

Views: 1217

Answers (4)

Joop Eggen
Joop Eggen

Reputation: 109597

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

Upvotes: 3

Bits Please
Bits Please

Reputation: 338

The result of adding Java chars, shorts, or bytes is an int

See the detailed answers on this post: In Java, is the result of the addition of two chars an int or a char?

Upvotes: 0

NiVeR
NiVeR

Reputation: 9796

In the second case there is an error because, by JLS 5.6.2 both operands of the binary expression are converted to int.

To make it work you should add explicit cast:

char c2=(char)('A'+c1);

Upvotes: 1

404 Brain Not Found
404 Brain Not Found

Reputation: 605

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

Upvotes: 1

Related Questions