How to convert int to char in Java

Today, in this tutorial, you will get to know how to convert int to char in Java. So you will learn how to convert int to char and see various methods to convert int to char in Java. Below you can see source codes of How to convert int to char in Java.

Methods to convert int to char

  1. Typecasting
  2. forDigit() method

Typecasting

Typecasting is basically converting one data type into another.

Code:

public class integertoChar {
   public static void main(String args[])
   {
      int a=65;
      char i=(char)a;
      System.out.println(i);
   }
}

Output

A

As ASCII value of A is 65, integer value 65 stored in a gets converted into its ASCII letter that is A. Here if the value of the variable lies between 0 and 48 different symbols are printed corresponding to the ASCII value if the value of variable a is 0 nothing gets printed on typecasting.

Another way to convert is by putting value in single inverted commas and then typecasting it.

public class integertoChar {
    public static void main(String args[])
    {
      int b='1';
      char j=(char)b;
      System.out.println(j);			
    }
}

Output:

1

Here value in inverted commas gets directly converted into char without ASCII stuff.

If we combine these two methods and add them we get the different results as shown below:

public class integertoChar {
    public static void main(String args[])
    {
     	int c=1;
        char k=(char)(c+'1');
        System.out.println(k);
    }
}

Output::

2

Here normal value stored in the variable c gets added with the value stored in the single inverted commas to get the output to 2.

forDigit() Method

This is the inbuilt function in Java that can be used for converting from int to char. It belongs to java.lang package. This function needs two parameters. First is the integer value and second is the specific radix format.

For example for getting hex value radix should be 16, for getting octal value radix should be 8, etc.

Below is the sample code::

public class integertoChar {
    public static void main(String args[])
    {
      char d1=Character.forDigit(4,10);   		
      char d2=Character.forDigit(13,16);   
      System.out.println("d1 ::"+d1);
      System.out.println("d2 ::"+d2);
    }
}

Output::

d1 ::4
d2 ::d

If the conversion is invalid, there is blank output.

 

Also read:: How to convert a character array to the string in Java?

Leave a Reply

Your email address will not be published. Required fields are marked *