Here we are explaining how to write a java program to convert a character to an integer.
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.
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
.
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.
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);
}
}
Enter any character m The Ascii Value of m is 109