Java Convert String to Character using Apache Commons Lang

Tags: Apache Commons Apache Commons Lang CharUtils Convert String Character

In this Java tutorial we learn how to convert a String object to a Character object 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 String object to Character object in Java

The Apache Commons Lang library provides the method CharUtils.toCharacterObject() to convert a String object to Character object using the first character of a given String object. You can learn how to use the CharUtils.toCharacterObject() method via the example code below.

ConvertStringToCharacter.java

import org.apache.commons.lang3.CharUtils;

public class ConvertStringToCharacter {
    public static void main(String... args) {
        String inputString1 = "Java";
        String inputString2 = "S";

        Character result1 = CharUtils.toCharacterObject(inputString1);
        Character result2 = CharUtils.toCharacterObject(inputString2);

        System.out.println("Converted Character value: " + result1);
        System.out.println("Converted Character value: " + result2);
    }
}
The output is:
Converted Character value: J
Converted Character value: S

Happy Coding 😊