javasystem.outcustom-data-type

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


I have the following code:

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

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

    }
}

Why does it output 98?


Solution

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