Question

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.

Was it helpful?

Solution

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'

OTHER TIPS

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

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top