The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Character Arithmetic

It may seem odd, but you can do arithmetic with characters! The expression 'a' + 1 yields the value 'b'. Similarly, if you have a variable named letter that contains a character, then letter - 'a' will tell you where in the alphabet it appears (keeping in mind that 'a' is the zeroeth letter of the alphabet and 'z' is the 25th).

This sort of thing is useful for converting between the characters that contain numbers, like '0', '1' and '2', and the corresponding integers. They are not the same thing. For example, if you try this

    char letter = '3';
    int x = (int) letter;
    System.out.println (x);

you might expect the value 3, but depending on your environment, you might get 51, which is the ASCII code that is used to represent the character '3', or you might get something else altogether. To convert '3' to the corresponding integer value you can subtract '0':

    int x = (int)(letter - '0');

Technically, in both of these examples the typecast ((int)) is unnecessary, since Java will convert type char to type int automatically. I included the typecasts to emphasize the difference between the types, and because I'm a stickler about that sort of thing.

Since this conversion can be a little ugly, it is preferable to use the digit method in the Character class. For example:

    int x = Character.digit (letter, 10);

converts letter to the corresponding digit, interpreting it as a base 10 number.

Another use for character arithmetic is to loop through the letters of the alphabet in order. For example, in Robert McCloskey's book Make Way for Ducklings, the names of the ducklings form an abecedarian series: Jack, Kack, Lack, Mack, Nack, Ouack, Pack and Quack. Here is a loop that prints these names in order:

    char letter = 'J';
    while (letter <= 'Q') {
      System.out.println (letter + "ack");

Notice that in addition to the arithmetic operators, we can also use the conditional operators on characters. The output of this program is:


Of course, that's not quite right because I've misspelled "Ouack" and "Quack." As an exercise, modify the program to correct this error.

Typecasting for experts

Here's a puzzler: normally, the statement x++ is exactly equivalent to x = x + 1. Unless x is a char! In that case, x++ is legal, but x = x + 1 causes an error.

Try it out and see what the error message is, then see if you can figure out what is going on.

Last Update: 2011-01-24