Convert words in a String into camelCase in Java using Apache Commons Text

Introduction

In this article we are going to explore Apache Commons Text library by using CaseUtils utility class to convert a String of separated words into a camelCase String.

Setup Apache Commons Text in Java project

If you are using Gradle build then add the following dependency configuration into build.gradle file.

compile group: 'org.apache.commons', name: 'commons-text', version: '1.9'

Or add the following dependency XML tag to pom.xml file if you are using Maven build.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

Or download commons-text-1.9.jar file from Apache Commons Text download page at commons.apache.org

CaseUtils.toCamelCase() with lowercase first character

Following Java code example to show how to use org.apache.commons.text.CaseUtils.toCamelCase() with lowercase first character output String.

import org.apache.commons.text.CaseUtils;

public class CaseUtilsToCamelCaseExample1 {
    public static void main(String[] args) {
        String result1 = CaseUtils.toCamelCase("Testing String", false);
        String result2 = CaseUtils.toCamelCase("testing String", false);
        String result3 = CaseUtils.toCamelCase("testing string", false);

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}
Output:

testingString
testingString
testingString

CaseUtils.toCamelCase() with uppercase first character

Following Java code example to show how to use org.apache.commons.text.CaseUtils.toCamelCase() with uppercase first character output String.

import org.apache.commons.text.CaseUtils;

public class CaseUtilsToCamelCaseExample2 {
    public static void main(String[] args) {
        String result1 = CaseUtils.toCamelCase("Testing String", true);
        String result2 = CaseUtils.toCamelCase("testing String", true);
        String result3 = CaseUtils.toCamelCase("testing string", true);

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}
Output:

TestingString
TestingString
TestingString

Happy Coding 😊