char arithmetic

Core Java · lesson 22 of 42 · 3 min read

Treat char as the number it really is, for letter maths, digits and simple ciphers.

Open this lesson in the learning hub

Key points

  • A char is an unsigned 16-bit number, so it joins in arithmetic: (int) 'J' is 74.
  • Arithmetic promotes a char to int, so 'J' + 1 is 75 until you cast back.
  • '7' - '0' turns a digit character into its value, and c - 'a' gives a letter its position in the alphabet.
  • Compare chars like numbers: c >= 'a' && c <= 'z' is a lower-case test.
  • Character.isLetter and isDigit follow the full Unicode rules — prefer them to hand-rolled ranges.
  • Reach the characters with charAt(i) or toCharArray(). A String is not itself a char array.

Example

public class Main {

    static boolean isVowel(char c) {
        return "aeiou".indexOf(Character.toLowerCase(c)) >= 0;
    }

    public static void main(String[] args) {
        char letter = 'J';
        System.out.println("'J' as an int is " + (int) letter);
        System.out.println("letter + 1 = " + (letter + 1) + ", cast back -> " + (char) (letter + 1));
        System.out.println("'z' - 'a' = " + ('z' - 'a') + " letters apart");
        System.out.println("digit char to value: '7' - '0' = " + ('7' - '0'));

        StringBuilder shifted = new StringBuilder();
        for (char c : "java".toCharArray()) {
            shifted.append((char) ('a' + (c - 'a' + 1) % 26));
        }
        System.out.println("Caesar shift \"java\" by 1 -> " + shifted);

        int vowels = 0;
        for (char c : "Programming".toCharArray()) {
            if (isVowel(c)) vowels++;
        }
        System.out.println("vowels in Programming: " + vowels);

        System.out.println("isLetter('J')=" + Character.isLetter('J')
                + ", isDigit('7')=" + Character.isDigit('7')
                + ", toUpperCase('j')=" + Character.toUpperCase('j'));
    }
}

A char is a number wearing a letter costume.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.