Java Program to convert character to integer

Here we are explaining how to write a java program to convert a character to an integer.

How to convert an integer number to a character in java?

In java, an integer number can be converted to a character by using type casting. An example is shown below.

int num=ch;

Here ch is the character that is converted into the integer number num. The num contains the ASCII value of the character ch.

How to implement the java program to convert character to an integer using type casting?

First, we have to declare the class IntToChar.Create an object of the scanner class as sc. Read the character from the user into the variable c. Convert the character c into the integer as int n=c. Now n contains the ASCII value of c. Then display n by using System.out.println.

 

ALGORITHM

STEP 1: Declare the class CharToInt with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Create an object of the scanner class as sc.

STEP 4: Read the character from user into the variable c using sc.next().charAt(0).

STEP 5: Convert the character c to integer as int n=c.

STEP 6: Display the integer number n.

Java Source Code

                                          import java.util.Scanner;
public class CharToInt{  
   public static void main(String args[]){  
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter any character");
 char c = sc.next().charAt(0);   
 int n= c;
 System.out.println("The Ascii Value of "+c+" is "+n);  
   }
}
                                      

OUTPUT

Enter any character
m
The Ascii Value of m is 109