Java Convert Character to int value using Apache Commons Lang

Tags: Apache Commons Apache Commons Lang CharUtils Convert Character int

In this Java tutorial we learn how to convert a Character object to an int value it represents using the CharUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to convert Character object into int value in Java

The Apache Commons Lang library provides the method CharUtils.toIntValue() to convert a Character object to an integer value it represents. The method only supports the input character range from ‘0’ to ‘9’ otherwise it throws a java.lang.IllegalArgumentException exception.

You can learn how to use the CharUtils.toIntValue() method with the following example code.

ConvertCharacterToInt.java

import org.apache.commons.lang3.CharUtils;

public class ConvertCharacterToInt {
    public static void main(String... args) {
        Character character = new Character('9');

        int intValue = CharUtils.toIntValue(character);

        System.out.println("Converted int value: " + intValue);
    }
}
The output is:
Converted int value: 9

Happy Coding 😊