Capitalize First Letter of each Word of String in Java using Apache Commons Text

Tags: Apache Commons Apache Commons Text WordUtils String

Introduction

In this article we show how to use WordUtils utility class of Apache Commons Text library to capitalize the first character of each word in a Java String. We will provide Java code examples to show how to use capitalize() and capitalizeFully() methods of the library’s WordUtils utility class.

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

Java Example code org.apache.commons.text.WordUtils.capitalize()

In the following Java code example we use WordUtils.capitalize() method to capitalize all words in a String separated by the whitespace and keep other characters as it is.

import org.apache.commons.text.WordUtils;

public class WordUtilsCapitalizeExample {
    public static void main(String[] args) {
        String result1 = WordUtils.capitalize("how to CAPITALIZE first letter words");
        System.out.println(result1);
    }
}
Output:

How To CAPITALIZE First Letter Words

Java Example code org.apache.commons.text.WordUtils.capitalizeFully()

The difference of using WordUtils.capitalizeFully() vs WordUtils.capitalize() is it capitalizes the first character of each word as well as lowercase other characters.

import org.apache.commons.text.WordUtils;

public class WordUtilsCapitalizeFullyExample {
    public static void main(String[] args) {
        String result1 = WordUtils.capitalizeFully("how to CAPITALIZE first letter words");
        System.out.println(result1);
    }
}
Output:

How To Capitalize First Letter Words

Happy Coding 😊