3

I have a Java fragment that looks like this:

    char ch = 'A';
    System.out.println("ch = " + ch);

which prints: A

then when I do this

    ch++; // increment ch
    System.out.println("ch =" + ch);

it now prints: B

I also tried it with Z and resulted to a [ (open square brace)
and with - and resulted to .


How did this happen? What can be the possible explanation for this? Thanks in advance.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Þaw
  • 2,047
  • 4
  • 22
  • 39

5 Answers5

9

For characters 0 to 127, you follow the ASCII character set.

enter image description here

As you can see the character after (90) Z is (91) [ and the character after (45) - is (46) .

Try

char ch = '-';
ch += '-'; // == (char) 90 or 'Z'

or even more bizarre

char ch = '0';
ch *= 1.15; // == (char) 48 * 1.15 = 54 or '6'
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • so when I incremented `ch` what value did it increment? is it the `dec, Hx, `or `Oct`? – Þaw Jun 25 '13 at 07:14
  • @Þaw Actually it is none of them. A char is a 16-bit binary value i.e. it has 16 bits. You can display this as a `char` as you have seen or as decimal, or hex, of octal, but really it is just a collection of bits. – Peter Lawrey Jun 25 '13 at 07:16
  • wow! I tried what you did sir and it worked, amazing HAHA. sorry for being ignorant :D still learning a lot. – Þaw Jun 25 '13 at 07:19
  • @Þaw Try the one I just added ;) '0' * 1.15 => '6' – Peter Lawrey Jun 25 '13 at 07:20
  • Sir I tried it it went to 7, Sir I've an additional question what is `'\u0000'` ? – Þaw Jun 25 '13 at 07:27
  • @Þaw It is just character 0, or the "nul" character. You can also write `'\0'` – Peter Lawrey Jun 25 '13 at 07:29
3

This happens because a 'char' is essentially a number, in Unicode format in which each character you type is represented by a number. This means that a character can be treated just like a number in that one can be added subtracted or anything else.

For more information on the specific mappings try here

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
1

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). Arithmetic operations can be performed on char literals because they are actually numeric values representing the Unicode.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

it is actually incrementing the ascii values. A s value is 65 so 66 is B. Again Z's value is 90 and [ is 91

stinepike
  • 54,068
  • 14
  • 92
  • 112
1

Char has an numerical representation of characters. If you try to cast it to int like int a = (int) 'A'; you'll get the char code. When you increment the char value, you'll move down in ASCII table, and get the next table value.

SeniorJD
  • 6,946
  • 4
  • 36
  • 53