×

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

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.