Characters: the char Type

One character at a time

A char holds exactly one character, in single quotes. charAt gives you one:

public class Main {
    public static void main(String[] args) {
        String word = "Hello";
        char first = word.charAt(0);
        System.out.println(first);
    }
}

Output

H

Checking what a character is

The Character class has handy yes/no checks:

Methodtrue when the character is...
Character.isLetter(c)a letter
Character.isDigit(c)a digit 0-9
Character.isUpperCase(c)a capital letter
Character.isWhitespace(c)a space, tab or new line
public class Main {
    public static void main(String[] args) {
        System.out.println(Character.isDigit('7'));
        System.out.println(Character.isLetter('7'));
        System.out.println(Character.toUpperCase('q'));
    }
}

Output

true
false
Q

Characters are secretly numbers

Each character has a code number ('A' is 65, 'a' is 97). So you can do maths with chars:

public class Main {
    public static void main(String[] args) {
        char c = 'A';
        System.out.println((int) c);
        char next = (char) (c + 1);
        System.out.println(next);
        System.out.println('7' - '0');
    }
}

Output

65
B
7

Tip: '7' - '0' gives the number 7. It's a quick way to turn a digit character into a real number.

HOME LABS COMMUNITY DASHBOARD