Get numeric value of a character in Java
This post will discuss how to get the numeric value of a character in Java.
To the numeric value of a character in Java, we can use any of the following methods:
1. Using String.valueOf() and Integer.parseInt() method
A simple solution to get the numeric value represented by the character is using the String.valueOf(char) method with the Integer.parseInt(String) method. The idea is to use the String.valueOf(char) method to convert the char to a string first, and then call the Integer.parseInt(String) method to return the integer value represented by the string argument. For example:
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { char c = '1'; int i = Integer.parseInt(String.valueOf(c)); System.out.println(i); // 1 } } |
2. Using Character.digit() method
We can also use the Character.digit(char, radix) static method from the Character class to get the numeric value represented by the character in the specified radix. For example, the following code will convert the character '1' to an integer 1.
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { char c = '1'; int i = Character.digit(c, 10); System.out.println(i); // 1 } } |
3. Using Character.getNumericValue() method
The Character class has another static method called Character.getNumericValue(char), which returns the corresponding integer value for the specified Unicode character. It can be used as follows:
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { char c = '1'; int i = Character.getNumericValue(c); System.out.println(i); // 1 } } |
4. Using - operator
Finally, we can get the numeric value of a character by subtracting '0' from it. This will work as the ASCII values of the digits 0 to 9 are consecutive, and their difference is equal to their numeric values. For example:
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { char c = '1'; int i = c - '0'; System.out.println(i); // 1 } } |
That’s all about getting the numeric value of a character in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)