Java Convert String to char using Apache Commons Lang

Tags: Apache Commons Apache Commons Lang CharUtils Convert String char

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

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

ConvertStringToChar.java

import org.apache.commons.lang3.CharUtils;

public class ConvertStringToChar {
    public static void main(String... args) {
        String inputString1 = "Simple Solution";
        String inputString2 = "T";

        char result1 = CharUtils.toChar(inputString1);
        char result2 = CharUtils.toChar(inputString2);

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

Happy Coding 😊