×

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is called an explicit conversion. There are two methods to convert int to char:

  • Using typecast operator
  • Using forDigit() method

Using typecast operator

Casting is when we explicitly convert from one primitive data type, or a class, to another.

Example

In this example, we have initialized 65 to the variable a. 65 is the ASCII value of A. We cast the number from an integer to char, converting it to the letter A.

public class inTocharExample
{
public static void main(String args[])
{
int a=65;
char ch=(char)a;
System.out.println("The character value of  an integer is: "+ch);
}
}

Output

The character value of an integer is: A
 

Remember: If you are assigning 1 to a variable and want to convert it into character, then nothing will be print on the console. Because it will store ASCII value of 1 that is SOH (start of heading) which is a non-printable character.

Example

In the following example, we have done the same as above mentioned. We have initialized 1 to the variable i of type int. In the next statement, we performed casting. In the println statement, we are trying to print the converted value of 1, but it will not print the character ch.

public class inTocharExample1
{ 
public static void main(String args[])
{ 
int i=1;    
char ch=(char)i;    
System.out.println("Nothing will be print "+ch); 
}
}

Output

Nothing will be print

To remove the above problem, we will add '0' (as a character not as a digit) to the integer i during casting. It returns the actual value in the character form. The ASCII value of '0' is 48. When we add 48 to 1, it becomes 49, which is the ASCII value of 1.

Example

public class inTocharExample2
{  
public static void main(String args[])
{  
int i=1;    
char ch=(char)(i+'0');    
System.out.println("Character value is: " +ch); 
}
}

Output

Character value is: 1

When we initialize '1' as a character to the variable i of type int, it will store actual character in ch variable and print the same.

Example

public class inTocharExample3
{  
public static void main(String args[])
{  
int i='1';    
char ch=(char)i;    
System.out.println("Character value is: " +ch); 
}
}

Output

Character value is: 1

Using forDigit() method

forDigit() is a built-in static method of Character class which belongs to java.lang package. It parses two arguments digit and radix and returns the character representation of digit in specified radix format.  It returns null if the digit or radix are invalid numbers.  The signature of the method is given below.

public static char forDigit(int digit, int radix)

Invalid conversions

The following conversions returns null.

char ch2=Character.forDigit(3,2);                    //Binary radix

char ch2=Character.forDigit(9,8);                  //Octal radix

char ch2=Character.forDigit(10,10);      //decimal radix    

char ch2=Character.forDigit(16,16);  //Hexa radix

Valid Conversions

char ch2=Character.forDigit(0,10);    

char ch2=Character.forDigit(15,16);    //returns f because decimal value of f is 15

We can conclude from the above conversions that digit must be less than the radix.

Example

public class inTocharExample4
{ 
public static void main(String args[])
{ 
char ch1=Character.forDigit(9,10);    //Octal radix format
char ch2=Character.forDigit(11,16);                 //Hexa radix format
System.out.println("9 representations in radix 10 format: "+ch1);   
System.out.println("11 representations in radix 16 format: "+ch2);
}
}

Output

9 representations in radix 10 format: 9
11 representations in radix 16 format: b

Related Topics

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.