Java Program to Convert char to int - The Coding Shala
Hey there, welcome back to another post. In this post, we are going to learn how to convert char to int in Java.
Java Program to Convert char to int
By using the below ways we can convert char to int in Java:
- Implicit type-casting or automatic type conversion by the compiler.
- Using Integer class's parseInt() method.
- Using Character class's getNumericValue() method.
Java Program:
/** * https://www.thecodingshala.com/ */ public class Main { public static void main(String[] args) { char ch1 = 'a'; char ch2 = '5'; // implicit type casting, it will give ASCII value // lower data type to higher int num1 = ch1; System.out.println("char value: " + ch1); System.out.println("int value: " + num1); int num2 = ch2 - '0'; // remove ASCII value of 0 to get actual int value System.out.println("char value: " + ch2); System.out.println("int value: " + num2); // using Integer.parseInt(String) int num3 = Integer.parseInt(String.valueOf(ch2)); System.out.println("char value: " + ch2); System.out.println("Converted int value using parseInt() method: " + num3); // using Character.getNumericValue(char) int num4 = Character.getNumericValue(ch2); System.out.println("Converted int value using getNumericValue() method: " + num4); } }
Output:
char value: a int value: 97 char value: 5 int value: 5 char value: 5 Converted int value using parseInt() method: 5 Converted int value using getNumericValue() method: 5
Other Posts You May Like
- Java Program to Convert int to long
- Java Program to Convert long to int
- Java Program to Convert int to char
- Java Program to Take Input From User
- Java Program to Check Armstrong Number
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment