Adding char and int

2019-01-11 21:01发布

问题:

To my understanding a char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. And therefore when I do:

char c = '1';
System.out.println(c);

The output 1 was exactly what I expected. So why is it that when I do this:

int a = 1;
char c = '1';
int ans = a + c;
System.out.println(ans);

I end up with the output 50?

回答1:

You're getting that because it's adding the ASCII value of the char. You must convert it to an int first.



回答2:

Number 1 is ASCII code 49. The compiler is doing the only sensible thing it can do with your request, and typecasting to int.



回答3:

You end up with out of 50 because you have told Java to treat the result of the addition as an int in the following line:

int ans = a + c;

Instead of int you declare ans as a char.

Like so:

final int a = 1;
final char c = '1';
final char ans = (char) (a + c);
System.out.println(ans);


回答4:

Because you are adding the value of c (1) to the unicode value of 'a', which is 49. The first 128 unicode point values are identical to ASCII, you can find those here:

http://www.asciitable.com/

Notice Chr '1' is Dec 49. The rest of the unicode points are here:

http://www.utf8-chartable.de/



回答5:

A char is a disguised int. A char represents a character by coding it into an int. So for example 'c' is coded with 49. When you add them together, you get an int which is the sum of the code of the char and the value of the int.



回答6:

'1' is a digit, not a number, and is encoded in ASCII to be of value 49.

Chars in Java can be promoted to int, so if you ask to add an int like 1 to a char like '1', alias 49, the more narrow type char is promoted to int, getting 49, + 1 => 50.

Note that every non-digit char can be added the same way:

'a' + 0 = 97
'A' + 0 = 65
' ' + 0 = 32


回答7:

'char' is really just a two-byte unsigned integer.

The value '1' and 1 are very different. '1' is encoded as the two-byte value 49.

"Character encoding" is the topic you want to research. Or from the Java language spec: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.1



标签: java char int