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?

Bitmap
  • 12,402
  • 16
  • 64
  • 91
  • possible duplicate of [In Java, is the result of the addition of two chars an int or a char?](http://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char) –  Jul 10 '15 at 22:59

7 Answers7

8

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

Aidanc
  • 6,921
  • 1
  • 26
  • 30
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.

Drew Gibson
  • 1,624
  • 3
  • 18
  • 22
  • just adding reference , though you can ask compiler to produce this table too http://www.asciitable.com/ – Geek Apr 27 '12 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);
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
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/

CodeClown42
  • 11,194
  • 1
  • 32
  • 67
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.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
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
user unknown
  • 35,537
  • 11
  • 75
  • 121
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

pamphlet
  • 2,054
  • 1
  • 17
  • 27