Why does ('1'+'1') output 98 in Java? [duplicate]
Asked Answered
T

6

15

I have the following code:

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

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

    }
}

Why does it output 98?

Theta answered 25/1, 2020 at 7:51 Comment(4)
Related: 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.Tompkins
Which output had you expected (if you had any expectations)? 2? 11? A compile-time error?Tompkins
Does this answer your question? Is there a difference between single and double quotes in Java?Libnah
Also see Concatenate chars to form String in java, which tells you how to build a string from char.Natividad
E
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 .

Equivalence answered 25/1, 2020 at 7:55 Comment(0)
T
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.

Teddi answered 25/1, 2020 at 7:53 Comment(1)
Char literals look like single character strings but aren’t.Celibacy
S
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.

Saving answered 25/1, 2020 at 7:56 Comment(0)
C
3

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

Christenachristendom answered 25/1, 2020 at 7:55 Comment(0)
W
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

Wellestablished answered 25/1, 2020 at 8:51 Comment(0)
P
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.

Premiership answered 30/1, 2020 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.