Convert Int Type Variables to Char in Java

Exercise:

Write a Java Program to convert int type variables to char.

1. Convert by typecasting

Click Here to View the Solution!
   public class IntToChar {
   public static void main(String[] args) {
     int num1 = 90;
     int num2 = 92;
  
     // convert int to char by typecasting
     char c1 = (char)num1;
     char c2 = (char)num2;
     System.out.println(c1);    
     System.out.println(c2);    
   }
 } 
Click Here to View the Output!
Z
\
Click Here to View the Explanation!
  • In this program, variables are converted from int to char type using type casting.
  • Initially we have created two variables num1 and num2 of the type integer.
  • num1 is being typecasted from an integer to a char variable.
  • Since the integers 90 and 92 are being typecasted, they will be treated as ASCII values against which the resultant characters will be Z and / respectively.

2.Convert using forDigit()

Click Here to View the Solution!
   public class IntToChar {
   public static void main(String[] args) {
     int num1 = 1;
     int num2 = 14;
     char c1 = Character.forDigit(num1, 10);
     char c2 = Character.forDigit(num2, 16);
  
  
     System.out.println(c1);    
     System.out.println(c2);    
   }
 } 
Click Here to View the Output!
1
e
Click Here to View the Explanation!
  • In this program, int type variables are converted to char type variables using a Character class method forDigit().

In the following expression: char c1 = Character.forDigit(num1, 10);

  • The value of num1 will be converted into character type using forDigit() method.
  • 10 and 16 determine if the conversion is into decimal (0-9) or hexadecimal (0-15) values for which the relevant radix value will be used along the integer which is to be converted in the forDigit() method. Similarly other radix values are used as needed.

3.Convert by adding ‘0’

Click Here to View the Solution!
   public class IntToChar {
   public static void main(String[] args) {
     int num1 = 1;
     int num2 = 29;
     char c1 = (char)(num1 + '0');
     char c2 = (char)(num2 + '0');
  
     // print value
     System.out.println(c1);    
     System.out.println(c2);    
   }
 } 
Click Here to View the Output!
1
M
Click Here to View the Explanation!
  • In this program, integer type variable is converted into char type by adding the character ‘0’ to the variable which is to be converted.
  • In the following expression: char c1 = (char)(num1 + '0' );
  • The character ‘0’ is added to num1 which implicitly converts this character into its ASCII equivalent. For ‘0’, the ASCII equivalent is 48. This value when added to num1 (1) makes the overall ASCII equal to 49. ASCII 49 is equal to the character ‘1’. Thus, the same value now has a different data type i.e. char making the output = ‘1’.
  • Simiarly it converts c2 to char type too.