W3docs

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:

  1. Using the Character.getNumericValue method:
char c = '5';
int i = Character.getNumericValue(c);
  1. Subtracting '0' from the character:
char c = '5';
int i = c - '0';
  1. Using the Character.digit method:
char c = '5';
int i = Character.digit(c, 10);
  1. Using Integer.parseInt with String.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.