15

I have the following code:

class Example{
    public static void main(String args[]){

        System.out.println('1'+'1');

    }
}

Why does it output 98?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Robin
  • 165
  • 7
  • Related: [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) I suspect that this question is a duplicate. I haven’t found the exact original yet. – Ole V.V. Jan 25 '20 at 09:10
  • 3
    Which output had you expected (if you had any expectations)? 2? 11? A compile-time error? – Ole V.V. Jan 25 '20 at 09:11
  • 1
    Does this answer your question? [Is there a difference between single and double quotes in Java?](https://stackoverflow.com/questions/439485/is-there-a-difference-between-single-and-double-quotes-in-java) – Matsemann Jan 29 '20 at 11:03
  • 1
    Also see [Concatenate chars to form String in java](//stackoverflow.com/q/16282368), which tells you how to build a string from char. – Martijn Pieters Feb 27 '20 at 13:06

6 Answers6

20

In java, every character literal is associated with an ASCII value which is an Integer.

You can find all the ASCII values here

'1' maps to ASCII value of 49 (int type).
thus '1' + '1' becomes 49 + 49 which is an integer 98.

If you cast this value to char type as shown below, it will print ASCII value of 98 which is b

System.out.println( (char) ('1'+'1') );

If you are aiming at concatenating 2 chars (meaning, you expect "11" from your example), consider converting them to string first. Either by using double quotes, "1" + "1" or as mentioned here .

Arun Gowda
  • 2,721
  • 5
  • 29
  • 50
6

'1' is a char literal, and the + operator between two chars returns an int. The character '1''s unicode value is 49, so when you add two of them you get 98.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
4

'1' denotes a character and evaluates to the corresponding ASCII value of the character, which is 49 for 1. Adding two of them gives 98.

3

49 is the ASCII value of 1. So '1' +'1' is equal to 49 + 49 = 98.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Jahangir
  • 161
  • 2
  • 7
1

'1' is chat literal and it’s represent ASCII value which is 49 so sum of '1'+'1'=98.

Here I am sharing ASCII table as image. If you count column wise start from 0 so 1 is comes at 49th place. Sorry I am attaching image for better explanation.

enter image description here

Muzzamil
  • 2,823
  • 2
  • 11
  • 23
1

'1' is a char literal, and the + operator between two chars returns an int. The character '1''s unicode value is 49, so 49 + 49 equals 98.

Wevaya
  • 11
  • 1