Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following code:

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

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

    }
}

Why does it output 98?

like image 559
Robin Avatar asked Jan 25 '20 07:01

Robin


People also ask

What is possible loss of precision error in Java?

“Possible loss of precision” occurs when more information is assigned to a variable than it can hold. If this happens, pieces will be thrown out. If this is fine, then the code needs to explicitly declare the variable as a new type.

What does 2L mean in Java?

When you place 2L in code, that is a long literal, so the multiplications promote the other int s to long before multiplication, making your calculations correct by preventing overflow. The basic rules here to know here are: Java has operator precedence.


2 Answers

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 .

like image 54
Arun Gowda Avatar answered Sep 18 '22 21:09

Arun Gowda


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

like image 34
Mureinik Avatar answered Sep 20 '22 21:09

Mureinik