×

How to Convert char to int in Java

How to Convert char to int in Java

When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to common data type before evaluating the expression. Java compiler follows certain rules to decide which variable’s data type is to be converted. It converts the lower data type to that of a higher data type implicitly. int occupies 4 bytes in the memory and char occupies 2 bytes.

When we perform the conversion from char to int, we get ASCII value (integer value) of the given character. It is called implicit typecasting or widening conversion or type promotion.

There are three ways to convert char to int.

  • Using implicit typecasting
  • Using getNumricValue() method
  • Using String.valueOf() method

Valid conversions

char ch='a'; 

char ch='A';          //alphabets

char ch='1';  //digits

char ch='@';     //special characters

char ch=' ';      //space (null character)

Using implicit typecasting

We are assigning char values to integer variables without any typecasting. The compiler automatically performs the conversion.

Example

In the following example, we have taken two variable ch1 and ch2 of char type and initialize 'z' and ‘>' into these variables respectively. There are two integer variables num1 and num2. We have assigned ch1 and ch2 into the variable num1 and num2, respectively. The first println statement prints the ASCII value of the character ch1, and the second println statement prints the ASCII value of the character ch2.

public class charTointExample
{ 
public static void main(String args[])
{ 
char ch1='z'; 
char ch2='>'; 
int num1=ch1; 
int num2=ch2; 
System.out.println ("ASCII value of” +ch1+ " is: " +num1); 
System.out.println ("ASCII value of” +ch2+ " is: " +num2); 
}
}

Output

ASCII value of z is: 122
ASCII value of > is: 62

Using getNumericValue() method

You can also use getNumericValue(char) method to convert char to int. This is the static method of Character class. It accepts char as an argument and returns equivalent int value which denotes the numeric value of the character. It returns -1 if the character contains space (null character) or any special character. The signature of the method is given below.

public static int getNumericValue(char ch)

Where ch is a character to be converted.

Example

In the following example, we have taken a variable ch of type char and initialize 'P' to it. num is a variable of type int that stores the numeric value of the character. Character is a class that invokes the getNumericValue() method. This method parses character as an argument and returns the corresponding numeric value. The println statement prints the numeric value of the character ch.

public class charTointExample1
{ 
public static void main(String args[])
{ 
char ch='P'; 
int num=Character.getNumericValue(ch); 
System.out.println("Numeric value of " +ch+ " is: " +num); 
}
}

Output

Numeric value of P is: 25

Using String.valueOf() method

The valueOf() is a method of String class. It accepts the character as an argument and returns the integer value of specified char value.

Remember: This method does not accept any special character and space (null character). Only alphabets and digits are allowed. If you initialize special character or space as a character, then it throws NumberFormatException.

Example

In the following example, we have taken a variable ch of type char and initialized 4 to it. Here, num is a variable of type int that stores the converted int value of char. String.valueOf(ch) method converts the char into String. Integer.parseInt() method parses the String as an argument and returns the corresponding integer value. The println statement prints the integer value of the character ch.

public class charTointExample2
{ 
public static void main(String args[])
{ 
char ch='4'; 
int num=Integer.parseInt(String.valueOf(ch)); 
System.out.println("Integer value of character is: " +num); 
}
}

Output

Integer value of character is: 4

Related Topics

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.