char-to-int-java

Char To Int Java

Java Convert char to int

We can convert char to int in java using various ways. If we direct assign char variable to int, it will return ASCII value of given character.

Java Convert char to int

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

1) Java char to int Example: Get ASCII value

Let’s see the simple code to convert char to int in java.

  1. public class CharToIntExample1{
  2. public static void main(String args[]){
  3. char c=‘a’;
  4. char c2=‘1’;
  5. int a=c;
  6. int b=c2;
  7. System.out.println(a);
  8. System.out.println(b);
  9. }}

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 Character.getNumericValue(char) method which returns an integer value.

  1. public class CharToIntExample2{
  2. public static void main(String args[]){
  3. char c=‘1’;
  4. int a=Character.getNumericValue(c);
  5. System.out.println(a);
  6. }}

Output:

1

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

Let’s see another example which returns integer value of specified char value using String.valueOf(char) method.

  1. public class CharToIntExample3{
  2. public static void main(String args[]){
  3. char c=‘1’;
  4. int a=Integer.parseInt(String.valueOf(c));
  5. System.out.println(a);
  6. }}

Output:

1