Incrementing a character in Java explanation

5.3k views Asked by At

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.

5

There are 5 answers

6
Peter Lawrey On BEST ANSWER

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

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

0
AllTooSir On

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.

0
stinepike On

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

0
SeniorJD On

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.