Lesson 3.1 · Strings
Characters Are Numbers
How char values map to numbers, how to test and convert characters, and the c - 'a' trick for indexing letters.
10 min
Think of it like this
Every character has a seat number in a big table (Unicode). 'a' sits in seat 97, 'b' in 98, and so on in order. Knowing letters sit in consecutive seats lets you do arithmetic with them: 'c' − 'a' is 2 because 'c' is two seats after 'a'.
1.char arithmetic
A Java char holds a character's code. Letters a–z are consecutive (97–122), as are A–Z (65–90) and digits 0–9 (48–57). So c - 'a' gives a letter's position 0–25, and c - '0' turns a digit character into its number.
Going back, (char) ('a' + 2) is 'c'. Without the cast, 'a' + 2 is the int 99.
public class Main {
public static void main(String[] args) {
char c = 'c';
System.out.println((int) c); // 99
System.out.println(c - 'a'); // 2
System.out.println('7' - '0'); // 7
System.out.println((char) ('a' + 25)); // z
System.out.println('a' + 2); // 99, an int
}
}Output
99
2
7
z
992.The Character helpers
Character.isLetterOrDigit(c), Character.isLetter(c), Character.isDigit(c), Character.isWhitespace(c), Character.toLowerCase(c) and Character.toUpperCase(c) save you from writing range checks by hand, and they handle non-English letters too.
public class Main {
public static void main(String[] args) {
String s = "A man, a plan!";
StringBuilder clean = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) clean.append(Character.toLowerCase(c));
}
System.out.println(clean);
}
}Output
amanaplanQuick check
How do you convert the string "472" to the number 472 without Integer.parseInt?
Remember
c - 'a'maps a lowercase letter to 0–25;c - '0'maps a digit to its value.- Cast back with
(char)when you need a character. - Use
Characterhelpers for letter, digit and case checks.
Common mistakes
- Printing
'a' + 1and expecting 'b' (it prints 98). - Assuming only lowercase letters when the problem allows uppercase or digits.