问题
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