×

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

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

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.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.