6

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

7 Answers 7

8

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.

1
  • just adding reference , though you can ask compiler to produce this table too asciitable.com
    – Geek
    Commented Apr 27, 2012 at 22:24
2

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);
1

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/

0

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.

3
  • It's not a 'disguised int', but it is an integer (whole number) value. Commented Apr 27, 2012 at 22:22
  • @goldilocks what you're saying is exactly what I meant. Commented Apr 27, 2012 at 22:23
  • 2
    Okay, but (to nitpick ;/) an int is a java type, and a char is not a disguise for an int type. It's a char, but it does have an integer value (as does an int). Commented Apr 27, 2012 at 22:24
0

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

'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

Not the answer you're looking for? Browse other questions tagged or ask your own question.