Signup/Sign In

How to convert Java int to char

In Java, an int can be converted into a char value using typecasting. This is because in order to convert a higher data type into a lower data type typecasting needs to be performed. The ASCII character associated with the integer value will be stored in the char variable.

'0' is added with the int variable in order to get the actual value of the char variable. Also ,Character.forDigit() method can be used.

Typecasting

The typecasting is done through the typecasting operator to convert a higher data type to a lower data type.

Example 1:

Here various cases are taken that converts the int to char accordingly.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		int n1 = 65;  
		char ch1 = (char)n1;  
		System.out.println(ch1);  

		int n2 = 98;    
		char ch2 = (char)n2;   
		System.out.println(ch2); 

		int n3 = 102;    
		char ch3 = (char)(n3);  
		System.out.println(ch3); 
	}
}


A
b
f

Conversion By using Character.forDigit() method

The forDigit() method is a part of Character class and returns the character for a specific digit in accordance with the radix value.

Example 2:

Here, the int value(digit) is converted into char in accordance with the radix value.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		int r1 = 10;
		int r2 = 16;
		int a = 7;   
		char ch1= Character.forDigit(a,r1);    
		System.out.println(ch1);
		char ch2 = Character.forDigit(a,r2);    
		System.out.println(ch2);
	}
}


7
7

Example 3:

Here, the int value(digit) is converted into char using the toString() and charAt() method. See the example below.

public class StudyTonight
{  
    public static void main(String[] args)
    {  
      int a = 1;
      char b = Integer.toString(a).charAt(0);
      System.out.println(b);
        
    }  
}


1



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.