Java Program to Convert Integer to Char

In this java program, we will learn about how to convert an integer(int) variable to a Character(char) value.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Convert Int to Char using Typecasting

Integer is a higher datatype when compared to Char. When converting a higher datatype to lower datatype, you have to manually cast Integer to char. This is also called narrowing typecasting. Here, the ASCII character of integer value will be stored in the char variable.

For Example, if you typecast integer 65 to a char variable, then the character equivalent to ASCII value 65(which is 'A') is stored in the char variable.

public class IntegerToChar1 {
  public static void main(String[] args) {
    int num = 65;
    // Typecasting int to char
    char ch = (char)num;
    System.out.println(ch);
  }
}
Output
A

Java Program to Convert Int to Char by Adding '0'

In Java, we can also convert the integer into a character by adding the character '0' with it. If you add '0' with int variable, it will return actual value in the char variable. The ASCII value of '0' is 48. So, if you add 1 with 48, it becomes 49 which is equal to '1'. The ASCII value of '1' is 49.

This approach is only valid for int value from 0 to 9.

public class IntegerToChar2 {
  public static void main(String[] args) {
    int num = 2;
    // Convert int to char
    char ch = (char)(num + '0');
    System.out.println(ch);
  }
}
Output
2

Java Program to Convert Int to Char using forDigit() method

The forDigit() function of the Character class may also be used to convert an int type variable to a char type.

public class IntegerToChar3 {
  public static void main(String[] args) {
    // Radix is 10 for decimal numbers for
    // binary it is 2
    int RADIX = 10;
    int num = 5;
    // Convert int to char
    char ch = Character.forDigit(num, RADIX);
    System.out.println(ch);
  }
}
Output
5