Example 1: Java Program to Convert int to char
class Main {
public static void main(String[] args) {
// create int variables
int num1 = 80;
int num2 = 81;
// convert int to char
// typecasting
char a = (char)num1;
char b = (char)num2;
// print value
System.out.println(a); // P
System.out.println(b); // Q
}
}
In the above example, we have int
type variables num1 and num2. Notice the line,
char a = (char)num1;
Here, we are using typecasting to covert an int
type variable into the char
type variable. To learn more, visit Java Typecasting.
Note that the int
values are treated as ASCII values. Hence, we get P for int
value 80 and Q for int
value 81. It is because the ASCII value of P and Q are 80 and 81 respectively.
Example 2: int to char by using forDigit()
We can also use the forDigit()
method of the Character
class to convert the int
type variable into char
type.
class Main {
public static void main(String[] args) {
// create int variables
int num1 = 1;
int num2 = 13;
// convert int to char
// for value between 0-9
char a = Character.forDigit(num1, 10);
// for value between 0-9
char b = Character.forDigit(num2, 16);
// print value
System.out.println(a); // 1
System.out.println(b); // d
}
}
Notice the expression,
char a = Character.forDigit(num1, 10);
We have used the forDigit()
method converts the specified int
value into char
value.
Here, 10 and 16 are radix values for decimal and hexadecimal numbers respectively. That is, if the int
value is between 0 to 9, we use 10 as radix value, if the int
value is between 0 to 15, we use 16, and so on.
To learn more about the forDigit()
method, visit Java Character.forDigit() (Official Oracle Documentation).
Example 3: int to char by adding '0'
In Java, we can also convert the integer into a character by adding the character '0' with it. For example,
class Main {
public static void main(String[] args) {
// create int variables
int num1 = 1;
int num2 = 9;
// convert int to char
char a = (char)(num1 + '0');
char b = (char)(num2 + '0');
// print value
System.out.println(a); // 1
System.out.println(b); // 9
}
}
In the above example, notice the line,
char a = (char)(num1 + '0');
Here, the character '0' is converted into ASCII value 48. The value 48 is added to the value of num1 (i.e. 1). The result 49 is the ASCII value of 1. Hence, we get the character '1' as the output.
Note: This is only applicable for int
value 0 to 9.