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

无人久伴 提交于 2020-05-14 14:50:12

问题


I have the following code:

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

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

    }
}

Why does it output 98?


回答1:


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

You can find all the ASCII values here

'1' maps to ASCII value of 49.
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




回答2:


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




回答3:


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




回答4:


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




回答5:


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




回答6:


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



来源:https://stackoverflow.com/questions/59907338/why-does-11-output-98-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!