JAVAProgramming language

Java Convert CHAR to INT

It is possible to convert the character to an integer by java by using a variety of methods. If we directly assign an int variable to char it will give ASCII value for the character.

If char variable contains an int value, we can get the int value by calling Character.getNumericValue(char) method. Alternatively, we could use String.valueOf(char) method.

1) Java char to int Example: Get ASCII value

Let’s take a look at the simple method to convert char into an int in Java.

public class CharToIntExample1{  
public static void main(String args[]){  
char c='a';  
char c2='1';  
int a=c;  
int b=c2;  
System.out.println(a);  
System.out.println(b);  
}}  

Output:

97
49

2) Java char to int Example: Character.getNumericValue()

Let’s see the simple code to convert char to int in java using the character.getNumericValue(char) method which returns an integer value.

public class CharToIntExample2{  
public static void main(String args[]){  
char c='1';  
int a=Character.getNumericValue(c);  
System.out.println(a);  
}}  

Output:

1

3) Java char to int Example: String.valueOf()

Let’s take a look at another example, which gives an integer value for the specified char value by using String.valueOf(char) Method.

public class CharToIntExample3{  
public static void main(String args[]){  
char c='1';  
int a=Integer.parseInt(String.valueOf(c));  
System.out.println(a);  
}}  

Output:

1
About author

A self-motivated, highly dedicated, and ambitious learner. Experienced Technical Content Writer with a demonstrated history of working in the e-learning industry.
Related posts
C++Programming language

C++ Recursion

JAVAProgramming language

Java Convert int to String

CProgramming language

C Dereference Pointer

JAVAProgramming language

Java Convert Strings to Character(char)