I ran the below code on my computer:
char ch = 'E';
System.out.print(ch + ++ch);
I expected EF
but the output was 139
.
Why is the ASCII value added and printed.
My question is why is the output is 139
not EF
?
I ran the below code on my computer:
char ch = 'E';
System.out.print(ch + ++ch);
I expected EF
but the output was 139
.
Why is the ASCII value added and printed.
My question is why is the output is 139
not EF
?
As @Nexevis already stated, adding 2 chars giving you an integer. (Here is why)
However, to solve your problem use String.valueOf(obj)
System.out.print(String.valueOf(ch) + String.valueOf(++ch));
It's because of the way Java stores char
variables.
In Java, char
is stored like an int
and therefore the numeric values of your characters are added when you do ch + ++ch
.
A char always holds it's ascii / unicode numeric value.
+
operator in Java is a Arithmetic operator so it is treated both char
values with there Arithmetic value of char E
i.e. 69
c+ ++c ==> 69 + 70 = 139
if you need to add two char as like concatenation of string you can do it like follows :
char ch ='E';
System.out.print(ch+""+ (++ch));