Java Program to Convert char to int - The Coding Shala

Home >> Java Programs >> Convert char to int

 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
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala