Multiple Approaches to Capitalize the First Letter of a String in Java

Nov 19, 2025 · Programming · 12 views · 7.8

Keywords: Java | String Manipulation | Capitalize First Letter

Abstract: This article explores various methods to capitalize the first letter of a string in Java, focusing on the core substring-based solution while supplementing with regex and Apache Commons Lang alternatives. Through comprehensive code examples and exception handling explanations, it aids developers in selecting optimal practices for different scenarios.

Introduction

String manipulation is a common task in Java programming. Specifically, converting the first letter of a string to uppercase while preserving the case of the remaining characters is a frequent requirement. For instance, transforming "hello world" into "Hello world". This conversion is useful in scenarios like user interface display and data formatting.

Problem Analysis

Given a string, the objective is to convert the first character to uppercase and leave the rest unchanged. Edge cases such as empty strings and null values must be considered. Here is a concrete example:

Input: "hello world"
Output: "Hello world"

If the input is an empty string, the output should also be empty. For null inputs, the handling depends on the specific implementation.

Core Solution: Using the substring Method

The most straightforward approach involves using the substring method of the String class to split the string into two parts: the first character and the remainder. The first character is then converted to uppercase using toUpperCase, and the two parts are concatenated.

Below is the complete implementation code:

public static String capitalizeFirstLetter(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }
    return input.substring(0, 1).toUpperCase() + input.substring(1);
}

Code Explanation:

Test Examples:

System.out.println(capitalizeFirstLetter("hello")); // Output: Hello
System.out.println(capitalizeFirstLetter("")); // Output: (empty string)
System.out.println(capitalizeFirstLetter(null)); // Output: null

Alternative Approach: Using Regular Expressions (Java 9+)

Starting from Java 9, regular expressions with Matcher.replaceFirst can be used to capitalize the first letter. This method matches the first character and replaces it with its uppercase version.

Implementation Code:

import java.util.regex.Pattern;

public static String capitalizeFirstLetterRegex(String input) {
    if (input == null) {
        return null;
    }
    return Pattern.compile("^.").matcher(input).replaceFirst(m -> m.group().toUpperCase());
}

Code Explanation:

Using Apache Commons Lang Library

If the project already depends on Apache Commons Lang, the StringUtils.capitalize method can be employed. It offers robust first-letter capitalization, including null safety and empty string handling.

First, add the dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Usage Example:

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.capitalize("hello world"); // Result: "Hello world"

Performance and Selection Recommendations

In practice, the substring method generally offers the best performance as it directly manipulates the string without regex matching. The regex approach excels in code conciseness but may be slightly slower. The Apache Commons Lang method is ideal for projects already using the library, providing additional robustness.

Recommendations based on project needs:

Conclusion

This article presented three methods to capitalize the first letter of a string in Java. The core substring solution is simple and efficient, suitable for most cases. The regex approach offers an alternative, while Apache Commons Lang provides convenience for library users. Developers should choose the appropriate method based on specific requirements and environment.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.