Java – Convert Int to Char
In this tutorial, we shall learn how to convert an integer value to a char value.
Firstly, we shall go through the process of narrowing primitive conversion, where we shall manually convert a value of a higher datatype to a value of lower datatype.
Secondly, we shall discuss about Character.forDigit() method, which is used to get the character representation of a number for a given radix.
1. Convert int to char using Narrow Casting
Int is a higher datatype when compared to that of Char datatype. So, when converting a higher datatype to lower datatype, you have to manually cast char to int. This is also called narrowing casting or narrowing primitive conversion.
To manually typecast int to char, place the type of lower datatype keyword before higher datatype value in parenthesis.
In the following example, we have a variable n
which is of int type. We shall typecast i
to char variable c
.
Java Program
/**
* Java Program - Convert Int to Char
*/
public class IntToChar {
public static void main(String[] args) {
int i = 69;
char c = (char) i;
System.out.println(c);
}
}
Output
E
2. Convert int to char using Integer.charValue() method
Character.forDigit() is a static method of Character class that returns a char value for the character determined by the digit (first argument) and radix (second argument).
In this example, we shall use Character.forDigit() method to get the representation of the digit in the given radix.
For example, the digit representation of 12
in hexa-decimal (radix 16) system is c
.
Java Program
/**
* Java Program - Convert Int to Char
*/
public class IntToChar {
public static void main(String[] args) {
char c1 = Character.forDigit(12, 16);
System.out.println(c1);
char c2 = Character.forDigit(8, 10);
System.out.println(c2);
}
}
Output
c
8
Conclusion
In this Java Tutorial, we learned how to write Java programs to convert an Int to Char.