Convert char to int in Java
Problem
A Java char is stored as a 16-bit number (its character code), so converting it to int gives that code — 'A' is 65 and the digit '7' is 55, not 7.
Given the characters 'A' and '7', print their character codes and the numeric value of the digit '7'.
Java Program
public class CharToInt {
public static void main(String[] args) {
char letter = 'A';
char digit = '7';
int code = letter; // widening: a char already is a number (its character code)
int digitCode = digit; // the code of the symbol '7', not the value 7
int digitValue = digit - '0'; // distance from '0' gives the actual digit
System.out.println("Code of 'A': " + code);
System.out.println("Code of '7': " + digitCode);
System.out.println("Value of '7': " + digitValue);
}
}Output
Core Logic
Assigning a char to an int gives its character code; subtracting '0' gives a digit's actual value, because the digits 0 to 9 have consecutive codes.
- 1
int code = letter;is a widening conversion, so no cast is needed;'A'becomes 65. - 2
int digitCode = digit;stores the code of the symbol'7', which is 55. - 3
digit - '0'computes 55 − 48 = 7, the value the digit represents. - 4Each result is printed on its own line.
'9' - '0' is 57 − 48 = 9, and '0' - '0' is 0, so the trick works for every digit.Key Point: Mixing up the two meanings is a common bug: summing the digits of "123" with (int) c gives 150 (49 + 50 + 51) instead of 6.
Key Concepts
Approach 2: Using Character.getNumericValue()
public class CharToIntGetNumericValue {
public static void main(String[] args) {
char[] samples = {'7', 'b', 'Z', '#'};
for (char c : samples) {
int value = Character.getNumericValue(c); // letters count as 10 to 35, -1 means no value
System.out.println("'" + c + "' -> " + value);
}
System.out.println("Character.digit('b', 16) -> " + Character.digit('b', 16)); // value in a given base
}
}
Output
Core Logic
Character.getNumericValue returns a character's value as a digit and extends it to letters, which count as 10 to 35 — useful for bases above 10.
- 1
'7'gives 7, the same as'7' - '0'. - 2
'b'gives 11 and'Z'gives 35, in either case. - 3Characters with no numeric value, like
'#', give -1. - 4
Character.digit(c, radix)limits the answer to one base, returning -1 if the digit is invalid there.
Character.digit('b', 16) is 11, since b is a valid hex digit; Character.digit('b', 10) would be -1.Key Point: Prefer Character.digit(c, 10) when parsing decimal input — it rejects letters that getNumericValue would quietly accept.
Key Concepts
Interview Questions
How do you convert an int digit back to a char?
(char) ('0' + digit) turns 7 into '7', and Character.forDigit(digit, 10) does the same.
What is the character code of 'a'?
- The lowercase letters 'a' to 'z' run from 97 to 122, and uppercase 'A' to 'Z' from 65 to 90.