4 ways to convert char to int in Java [Practical Examples]
In Java, the char and an int are a primitive data types. In real life applications, many times we will need to convert the value of one type to the other type. So, Java provides the mechanism for this conversion. As we know, the char type in java can hold a single character whereas an int type holds the numbers without decimal. Here, we will see several ways to convert a char to its equivalent int.
- Using ASCII Values
- Using Integer.parseInt() method
- Using Character.getNumericValue() method
- Subtracting ‘0’
Using ASCII Values
This is the simplest approach to convert char to int in Java. Here, there are two ways to accomplish this task. The first way is through an implicit type conversion, where we assign the value of char variable to int variable. So, it stores the equivalent ASCII value in int type. The other way is explicit type conversion, where we do not use int variable but we write a int in the bracket for type conversion.
Example : In this example, we are showing both implicit and explicit type conversions.
Using Integer.parseInt() method
In this approach, we are using the static method parseInt of Integer wrapper class. It takes one parameter of string type and converts it to integer. So, we would need to convert char to string in order to use parseInt function.
Example : In this example, char variables are converted to int using parseInt method and valueOf method.
Using Character.getNumericValue() method
In this approach, we will use getNumericValue() method which is a static method of Character wrapper class. This method returns an equivalent int value that the specified Unicode character represents.
Example : In this example, char variables are converted to int using getNumericValue method of Character class.
Subtracting ‘0’
In this approach, we are simply subtracting the character ‘0’ from the other character. That means, if we subtract ‘0’ (ASCII equivalent 48) from any character let’s say ‘2’ (ASCII equivalent 50), we will get 2 as a result. Which means, ‘2’-‘0’=2.
Example : In this example, char variables are converted to int by subtracting character ‘0’ from the other character.
Examples Showing conversion of char to int
Example 1 : Evaluating expression stored in String
In this example, we are evaluating the expression stored in the string after converting the numbers to equivalent int value.
Example 2 : Find the summation of numbers stored in the String
In this example, we are finding the summation of the numbers after converting the numbers to equivalent int value.
Example 3 : Find the product of numbers stored in the String
In this example, we are finding the product of the numbers after converting the numbers to equivalent int value.
Example 4 : Convert the multi digit numbers stored in String to int
In this example, we are converting the multi digit number stored in the string to its equivalent int value.
Summary
The knowledge of converting char value to a int in Java is very useful while working on real time applications. In this tutorial, we covered four different approaches to convert char to int in Java. As per the requirement of an application, we can choose an appropriate approach for conversion. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on conversion of char value to a int value in Java.
Java Convert char to int with examples
In this tutorial, we will see how to convert a char to int with the help of examples. Converting a character to an integer is equivalent to finding the ASCII value (which is an integer) of the given character.
Java char to int – implicit type casting
Since char is a smaller data type compared to int, thus we do not need to do explicit type casting here. A simple assignment of char value to an int variable would do the trick, compiler automatically convert the char to int, this process is known as implicit type casting or type promotion.
In the following example we are assigning char values to integer variables without any typecasting. Compiler automatically doing the conversion here, this only applies when we are assigning a smaller data type to larger data type else we have to do explicit type casting.
Output:
Java char to int conversion using Character.getNumericValue()
We can also use Character.getNumericValue(char ch) method to convert a char to an int. This method accepts char as an argument and returns equivalent int (ASCII) value after conversion.
Here we have two char variables ch and ch2 and we are converting them to integers num and num2 using Character.getNumericValue() method.

Output:
Java char to int using Integer.parseInt() method
Here we are using Integer.parseInt(String) method to convert the given char to int. Since this method accepts string argument we are converting char to String using String.valueOf() method and then passing the converted value to the method.

Output:
Char to Int in Java
There are different ways to convert a character to its corresponding integer representation.
- Assigning a character to an integer-type variable gives the ASCII value of the character.
- Use Character.getNumericValue() method
- Convert the character to a String using String.valueOf() method and use Integer.parseInt() method.
- Subtract '0' from the character.
Scope of Article
This article aims to:
- Discuss the conversion of a character to an integer using:
- ASCII values
- Character.getNumericValue()
- parseInt() method with String.valueOf()
- char to int by subtracting with '0'
How to convert char to int in Java?
Sometimes we need to perform operations on integer values, here in this case it may be possible that the int value is stored in a char data type. In this situation, we first need to convert the char value to its corresponding integer value and then do the required operation.
The primitive data type can be converted from char to int data type in java using several ways:-
- Using ASCII values: We can automatically convert a character to its ASCII value by using implicit typecasting.
- Character.getNumericValue(): We can convert char to int using getNumericValue() method of the Character class.
- Using parseInt() method with String.valueOf(): We can convert char to int in java by converting char to string using String.valueOf() and then converting string to int using Integer.parseInt() method.
- Subtracting with '0': we can convert char to int by subtracting with 0 , this works on the concept of ASCII values.
Method 1: Using ASCII values
American Standard Code for Information Interchange is an encoding format used to store characters on a computer, it is a 7 — bit character set containing 128 characters.
In Java programming language we have implicit typecasting, i.e if we store the value of a smaller datatype to a variable of the larger datatype, then the value is automatically converted. This means that the variable is implicitly typecasted into a larger datatype variable.
Example:
Explanation:
- So in this example variable first is implicitly typecasted to int datatype and then stored in second variable.
- So now if we print the second variable it will print 53 . This is because we have assigned the char variable first to the int variable second and we get the ASCII value of 5 i.e. 53.
Example: 53-48 = 5
Below is the java program to convert char to int in java using the ASCII value:-
Output:
Method 2: Using Character.getNumericValue()
In Java, we have a method getNumericValue() inside the Character class. This method returns an int value which is the encoding of a Unicode character.
Syntax:
This method takes an argument of char datatype and returns the corresponding int value.
Example:
Output:
Method 3: parseInt() method with String.valueOf()
In java we can also convert from char to int java using the parseInt() and String.valueOf() methods.
- The String.valueOf(): method converts a char datatype variable into a string datatype variable and,
- Integer.parseInt(): method is used to convert string into an int datatype.
The method valueOf() belongs to String class and parseInt() method belongs to Integer class.
Example:
Output:
Explanation:
- Here in this example, ch1 is first converted to string using String.valueOf() and then it is converted to int using Integer.parseInt() .
- Similar operations are performed with ch2 character as well.
Method 4: Subtraction with '0':
In Java we can also convert the numeric value stored in a char to int datatype by subtracting it with the character 0 (zero). This is based on the concept of ASCII values.
If we want to convert char to int, we will subtract '0' from the character.
Преобразование между char и int в Java
В этом посте будет обсуждаться преобразование между char и int в Java.
1. Преобразование char в int
Чтобы преобразовать символ в целое число, вы можете использовать любой из следующих методов:
1. Неявное преобразование
Простое решение — воспользоваться преимуществом неявного преобразования компилятором, когда значение char присваивается целому числу, как показано ниже:
2. Использование String.getBytes() метод
Строка может быть преобразована в последовательность байтов с помощью getBytes() метод, который возвращает массив байтов. Чтобы сделать это для одного символа, используйте как:
3. Использование Character.digit() метод
Если вам нужно числовое значение, представленное символом в указанной системе счисления, вы можете использовать Character.digit() метод. Например,
2. Преобразование int в char
Чтобы преобразовать целое число в символ, вы можете использовать любой из следующих методов:
1. Использование кастинга
Если ваше целое число представляет диапазон символов ASCII, вы можете просто преобразовать его в символ без потери точности.
Чтобы получить соответствующее символьное представление указанной цифры, вы можете сделать следующее:
2. Использование Character.forDigit() метод
Стандартное решение для получения символьного представления для конкретной цифры в указанной системе счисления использует Character.forDigit() метод.
Чтобы преобразовать указанный символ (кодовая точка Unicode) в его представление UTF-16, вы можете использовать Character.toChars() метод, который возвращает массив символов.
Это все о преобразовании между char и int в Java.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 1
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования