Java Program For Int to Char Conversion
Last Updated :
08 Jan, 2024
In this article, we will check how to convert Int to Char. In Java, char takes 1 byte while int takes 4 bytes. So if we want the integer to get converted to a character then we need to typecast because data residing in 4 bytes can not get into a single byte.
Here the input provided to us is an integer value say it be ‘N’ and the task is to convert the number in characters.
Example of Int to Char Conversion
Input : N = 74254
Output : Seven four two five four
Input : N = 23
Output : Two three
Methods for Int to Char Conversion in Java
- Using the concept of typecasting (Naive Approach)
- Using Character.forDigit() function
Let us discuss each of the above-listed methods by laying out their corresponding approach and implementing them with the help of clean Java codes.
1. Using the concept of Type-casting
Here we will simply explicitly typecast the datatype and will store it into character. As we all know there is an ASCII table that holds a specific value corresponding to 256 symbols of the English language. So automatically it will store the corresponding symbol corresponding to the digit.
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int i = 97 ;
char ch = ( char )i;
System.out.println(ch);
}
}
|
Similarly, we can do the same via adding zero to the integer value and later on we will do the same as we did in the above example that is we will typecast the above same.
Example:
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
int i = 64 ;
char ch = ( char )(i + '0' );
System.out.println(ch);
}
}
|
Tip: It is also recommended to go through difference between type conversion and type casting in java.
2. Using Character.forDigit() for Converting Int to Char
This method using for converting integers to char, where we convert based on the base value of the Number. Converting is all based upon the base value it can’t be misunderstood by ASCII value.
Example 1:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int base = 10 ;
int a = 5 ;
char ans = Character.forDigit(a, base);
System.out.println(ans);
}
}
|
Example 2:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int base = 16 ;
int a = 1 ;
while (a < 16 ) {
char ans = Character.forDigit(a, base);
System.out.print(ans+ " " );
a++;
}
}
}
|
Output
1 2 3 4 5 6 7 8 9 a b c d e f
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...