Java How to Convert Char to Int with Examples
In Java, convert a
char to int by casting like int num = (int) ch; or by using Character.getNumericValue(ch); to get the numeric value.Examples
Input'5'
Output53
Input'A'
Output65
Input'9'
Output57
How to Think About It
To convert a character to an integer in Java, you can either get its ASCII code by casting it to int or get its numeric digit value if it represents a number. Casting gives the Unicode number, while using
Character.getNumericValue() returns the actual digit value for number characters.Algorithm
1
Take the input character.2
If you want the ASCII/Unicode code, cast the character to int.3
If you want the numeric digit value, use Character.getNumericValue() method.4
Return the resulting integer.Code
java
public class CharToInt { public static void main(String[] args) { char ch = '5'; int asciiValue = (int) ch; int numericValue = Character.getNumericValue(ch); System.out.println("ASCII value: " + asciiValue); System.out.println("Numeric value: " + numericValue); } }
Output
ASCII value: 53
Numeric value: 5
Dry Run
Let's trace converting char '5' to int using casting and getNumericValue.
1
Cast char to int
char ch = '5'; int asciiValue = (int) ch; // asciiValue = 53
2
Use getNumericValue
int numericValue = Character.getNumericValue(ch); // numericValue = 5
| Operation | Result |
|---|---|
| (int) '5' | 53 |
| Character.getNumericValue('5') | 5 |
Why This Works
Step 1: Casting char to int
Casting a char to int returns its Unicode (ASCII) numeric code.
Step 2: Using Character.getNumericValue
This method converts a digit character to its actual integer value, e.g., '5' to 5.
Alternative Approaches
Subtract '0' from char
java
public class CharToIntAlt { public static void main(String[] args) { char ch = '7'; int num = ch - '0'; System.out.println(num); } }
This works only if the char is a digit ('0' to '9'). It is fast and simple.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion is a simple arithmetic or method call, so it runs in constant time.
Space Complexity
No extra memory is needed besides the integer variable to store the result.
Which Approach is Fastest?
Subtracting '0' is fastest but only works for digit chars; casting and getNumericValue are more general.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Casting (int) ch | O(1) | O(1) | Getting ASCII/Unicode code |
| Character.getNumericValue(ch) | O(1) | O(1) | Getting digit value for any numeric char |
| Subtract '0' from char | O(1) | O(1) | Fast digit char to int conversion |
Use
ch - '0' to convert digit chars to int quickly when sure input is a digit.Trying to cast a digit char to int expecting the digit value instead of its ASCII code.