Capitalize First Letter of a String in Java using Apache Commons Lang

Tags: Apache Commons Apache Commons Lang StringUtils String

Introduction

In this article we show how to use StringUtils of Apache Commons Lang library to capitalize the first character of a Java String by using StringUtils.capitalize() utility method.

Setup Apache Commons Lang 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-lang3', version: '3.11'

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-lang3</artifactId>
    <version>3.11</version>
</dependency>

Or download commons-lang3-3.11.jar file from Apache Commons Lang download page at commons.apache.org

Code example how to use org.apache.commons.lang3.StringUtils.capitalize()

import org.apache.commons.lang3.StringUtils;

public class StringUtilsCapitalizeExample {
    public static void main(String[] args) {
        String result1 = StringUtils.capitalize("how to capitalize a string.");
        System.out.println(result1);

        String result2 = StringUtils.capitalize("java");
        System.out.println(result2);

        String result3 = StringUtils.capitalize("jAva");
        System.out.println(result3);

        String result4 = StringUtils.capitalize("'java'");
        System.out.println(result4);
    }
}
Output:

How to capitalize a string.
Java
JAva
'java'

Happy Coding 😊