Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll shed light on how to capitalize the first character of each word of a particular string in Java.

First, we’re going to explain how to do it using JDK built-in solutions. Then, we’ll demonstrate how to accomplish the same outcome using external libraries such as Apache Commons.

2. Introduction to the Problem

The main objective here is to convert the first letter of each word in a given string to uppercase. For instance, let’s say we have an input string:

String input = "Hi my name is azhrioun";

So, we expect to have an output where each word starts with an uppercase character:

String output = "Hi My Name Is Azhrioun";

The basic idea to tackle the problem is splitting the input string into several words. Then, we can use different methods and classes to capitalize the first character of each returned word.

So, let’s take a close look at each approach.

3. Using Character#toUpperCase

toUpperCase() provides the easiest way to achieve our goal. As the name indicates, this method converts a given character to uppercase.

So here, we’ll be using it to convert the first character of each word of our string:

static String usingCharacterToUpperCaseMethod(String input) {
    if (input == null || input.isEmpty()) {
        return null;
    }

    return Arrays.stream(input.split("\\s+"))
      .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
      .collect(Collectors.joining(" "));
}

As we can see, we started by checking if our string is null or empty to avoid potential NullPointerException. Then, we used the split() method to divide our input string into multiple words.

Furthermore, we used charAt(0) to get the first character of each word. Then, we applied toUpperCase() to the returned character. Afterward, we concatenated the uppercase character with the rest of the word using the + operator and substring(1).

Finally, we used Collectors#joining to join each capitalized word in a single string back again.

Now, let’s add a test case for our method:

@Test
void givenString_whenUsingCharacterToUpperCaseMethod_thenCapitalizeFirstCharacter() {
    String input = "hello baeldung visitors";

    assertEquals("Hello Baeldung Visitors", CapitalizeFirstCharacterEachWordUtils.usingCharacterToUpperCaseMethod(input));
}

4. Using String#toUpperCase

The String class provides its own version of the toUpperCase() method. So, let’s rewrite the previous example using String#toUpperCase:

static String usingStringToUpperCaseMethod(String input) {
    return Arrays.stream(input.split("\\s+"))
      .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
      .collect(Collectors.joining(" "));
}

As shown above, we used substring(0, 1) to extract the first character of each word as a String. Then, we called the toUpperCase() method to convert it to uppercase. Subsequently, we used the same mechanism as before to concatenate and join the returned words.

Let’s write the test for this approach:

@Test
void givenString_whenUsingSubstringMethod_thenCapitalizeFirstCharacter() {
    String input = "Hi, my name is azhrioun";

    assertEquals("Hi, My Name Is Azhrioun", CapitalizeFirstCharacterEachWordUtils.usingStringToUpperCaseMethod(input));
}

Please bear in mind that, unlike String#toUpperCase, Character#toUpperCase is a static method. Another key difference is that String#toUpperCase produces a new String, whereas Character#toUpperCase returns a new char primitive.

5. Using StringUtils From Apache Commons Lang3

Alternatively, we can use the Apache Commons Lang3 library to address our central question. First, we need to add its dependency to our pom.xml:

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

This library provides the StringUtils class to manipulate and handle strings in a null-safe manner.

So, let’s see how we can use this utility class to capitalize each word of a specific string:

static String usingStringUtilsClass(String input) {
    return Arrays.stream(input.split("\\s+"))
      .map(StringUtils::capitalize)
      .collect(Collectors.joining(" "));
}

Here, we used the capitalize() method which, as the name implies, converts the first character to uppercase. The remaining characters of the given string are not changed.

Lastly, let’s confirm our method using a new test case:

@Test
void givenString_whenUsingStringUtilsClass_thenCapitalizeFirstCharacter() {
    String input = "life is short the world is wide";

    assertEquals("Life Is Short The World Is Wide", CapitalizeFirstCharacterEachWordUtils.usingStringUtilsClass(input));
}

6. Using WordUtils From Apache Commons Text

Another solution would be using the Apache Commons Text library. Without further ado, let’s add its dependency to the pom.xml file:

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

Typically, this library comes with a set of ready-to-use classes and methods for string operations. Among these classes, we find WordUtils.

The WordUtils#capitalizeFully method offers the most concise and straightforward way to tackle our problem. This method converts all the whitespace-separated words into capitalized words.

Please note that this method handles null input gracefully. So, we don’t need to check whether our input string is null or not.

Now, let’s add another test case to make sure that everything works as expected:

@Test
void givenString_whenUsingWordUtilsClass_thenCapitalizeFirstCharacter() {
    String input = "smile sunshine is good for your teeth";

    assertEquals("Smile Sunshine Is Good For Your Teeth", WordUtils.capitalizeFully(input));
}

7. Conclusion

In this short article, we explored different ways to capitalize the first letter of each word of a given string in Java.

First, we explained how to achieve this using the JDK. Then, we illustrated how to answer our central question using third-party libraries.

As always, the code used in this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.