Converting characters to integers in Java
There are a few ways to convert a character to an integer in Java.
There are a few ways to convert a character to an integer in Java. Here are several options:
- Using the
Character.getNumericValuemethod:
char c = '5';
int i = Character.getNumericValue(c);- Subtracting
'0'from the character:
char c = '5';
int i = c - '0';- Using the
Character.digitmethod:
char c = '5';
int i = Character.digit(c, 10);- Using
Integer.parseIntwithString.valueOf:
char c = '5';
int i = Integer.parseInt(String.valueOf(c));Note that these methods handle non-digit characters differently. Character.getNumericValue supports Unicode digits beyond 0-9 and returns -1 for non-digits. Character.digit also returns -1 for invalid digits. Subtracting '0' performs simple arithmetic and will return a positive offset (e.g., 'a' - '0' equals 17), so it does not validate input.