Get character representation of a specific digit in Java
This post will discuss how to get the character corresponding to the given digit between 0 and 9 in Java.
1. Using Character.forDigit() method
The standard solution to get the character representation of a specific digit is to use Character.forDigit() method. It returns the char value represented by the integer in the specified radix. For example:
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { int digit = 1; char c = Character.forDigit(digit, 10); System.out.println(c); // '1' } } |
2. Using Casting
Another alternative is casting, which is explicitly converting one type to another. We can get the corresponding character representation of the specified digit by adding ‘0’ to it and then casting the result to a char. For example:
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { int digit = 1; char c = (char) (digit + '0'); System.out.println(c); // '1' } } |
3. Using String.valueOf() method
Finally, we can call String.valueOf(int) method to get the string representation of the given digit and then extract the character present at the first index with String.charAt(index) method. For example:
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { int digit = 1; char c = String.valueOf(digit).charAt(0); System.out.println(c); // '1' } } |
That’s all about getting the character representation of a specific digit 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 :)