Java Program to Convert Char to Int

Write a Java program to convert char to int with an example. In this language, we don’t have to do anything to convert a character to an integer because it is an implicit typecasting.

Java Program to Convert Char to Int

Instead, we have to assign the character to an integer variable. This example accepts the user input character and converts it to int.

package NumPrograms;

import java.util.Scanner;

public class CharToInt1 {
	private static Scanner sc;	
	
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);	

		System.out.print("Please Enter any Character =  ");
		char ch = sc.next().charAt(0);
		
		int i = ch;

		System.out.println("The ASCII Value of " + ch + "  = " + i);
		System.out.format("The ASCII Value of %c  = %d", ch, i);
	}
}
Java Program to Convert Char to Int

This Java program uses the getNumericValue method to convert the character to an integer or char to int.

package NumPrograms;

import java.util.Scanner;

public class CharToInt2 {
	private static Scanner sc;	
	
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);	

		System.out.print("Please Enter any Character =  ");
		char ch = sc.next().charAt(0);
		
		int i = Character.getNumericValue(ch);

		System.out.println( i);
	}
}
Please Enter any Character =  q
26

If the given character is a numeric value, then we can use the Java Integer.parseInt method. However, it accepts the string, so we have to convert the character to string. This example uses this method to convert char to an integer.

package NumPrograms;

public class CharToInt3 {
	
	public static void main(String[] args) {

		char ch1 = '8';
		char ch2 = '5';
		
		int i = Integer.parseInt(String.valueOf(ch1));
		int j = Integer.parseInt(String.valueOf(ch2));

		System.out.println(i);
		System.out.println(j);
	}
}
8
5

Please refer to the Convert Character Array To String and Convert Character to String articles.