How to convert Char to Int in Java?

If you are looking for a really simplified approach to convert a character to integer in Java, you have landed on the right place.In this example, we will explain how easy it is to convert a char to integer, in Java using Apache commons-lang3-3.1.

Download Apache Commons-lang and have the JAR file commons-lang3-3.1.jar in your classpath, for the example to work. [We will use org.apache.commons.lang3.CharUtils for this example]

Java – Char to Int – Example


The code to convert character to integer, in Java is given below:
import org.apache.commons.lang3.CharUtils;
public class CharToInt {
  public static void main(String[] args) throws Exception {
    System.out.println("About to convert character '3' to integer ");
    char myChar='3';
    int myInt=CharUtils.toIntValue(myChar);
    System.out.println("converted Integer " + myInt);      
  }
}

Char to Int – Exception


In the above code block, what would happen if we tried to convert a non numeric character to Integer, as an example character “a”. You will get a runtime exception as below.

java -classpath .;commons-lang3-3.1.jar CharToInt
About to convert character 'a' to integer
Exception in thread "main" java.lang.IllegalArgumentException: The character a is not in the range '0' - '9'
        at org.apache.commons.lang3.CharUtils.toIntValue(CharUtils.java:219)
        at CharToInt.main(CharToInt.java:6)

Handle Int Conversion Exceptions


Is there a way to suppress IllegalArgumentException, and assign a default value if the character is not numeric? Yes, it is possible to assign a default value. (You can alternatively have a try catch block) but Common components library simplifies this. An Example is shown below:

import org.apache.commons.lang3.CharUtils;
public class CharToInt {
  public static void main(String[] args) throws Exception {
    System.out.println("About to convert character 'a' to integer ");
    char myChar='a';
    //Here we assign a default value of 1, if the input character cannot be 
    //converted to integer
    int myInt=CharUtils.toIntValue(myChar,1);
    System.out.println("converted Integer " + myInt);      
  }
}

In the code segment above, though character “a” cannot be converted to integer, instead of throwing an exception, a default value of 1 is returned.

No comments:

Post a Comment