0

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?

Nexevis
  • 4,647
  • 3
  • 13
  • 22
  • 2
    Adding two `char` values in Java returns an `int`. If you did `System.out.print(ch + "" + ++ch);` instead, the result would be `EF`. See this [post](https://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char). – Nexevis Jan 29 '20 at 16:02
  • 3
    Does this answer your question? [In Java, is the result of the addition of two chars an int or a char?](https://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char) or [How to concatenate characters in java?](https://stackoverflow.com/questions/328249/how-to-concatenate-characters-in-java) – jhamon Jan 29 '20 at 16:02

3 Answers3

1

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));
gkhaos
  • 694
  • 9
  • 20
1

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.

Fred
  • 220
  • 2
  • 8
1

+ 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));
Ajinkya
  • 325
  • 3
  • 12
  • 1
    @Subrat Singh Is your query resolved ? Can you please accept my answer it you got the answer for your question – Ajinkya Jan 29 '20 at 16:28