Capitalize the first letter of each word in a string using Java

In this short guide, you will learn how to capitalize the first letter of each word in a string using Java. We have already learned to capitalize the first letter of a string in Java. But capitalizing each word in a string is a bit tricky.

Using Java 8 Streams

The easiest way to capitalize the first character of each word of a string is by using Java 8 Stream API:

String str = "welcome to java";

// uppercase first letter of each word
String output = Arrays.stream(str.split("\\s+"))
        .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
        .collect(Collectors.joining(" "));

// print the string
System.out.println(output);
// Welcome To Java

In the above example, we first split the string into an array using the split() method. The array is passed to Arrays.stream() as a parameter that turns it into a Stream object. Afterward, we use the map() method from streams to capitalize each word before converting it back to a string using the collect() method.

If the string is empty or null, the above code will throw an exception. Let us write a function capitalizeAll() that makes sure there is no exception while transforming string:

public static String capitalizeAll(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    return Arrays.stream(str.split("\\s+"))
            .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
            .collect(Collectors.joining(" "));
}

Here are a few examples that use the above function to capitalize the first character of each word:

System.out.println(capitalizeAll("welcome to java")); // Welcome To Java
System.out.println(capitalizeAll("this is awesome")); // This Is Awesome
System.out.println(capitalizeAll("mcdonald in lahore")); // Mcdonald In Lahore
System.out.println(capitalizeAll(null)); // null

The above solution only changes the first letter of each word while all other characters remain the same.

Sometimes, you want to ensure that only the first character of a word is capitalized. Let us write another function capitalizeFully() for this:

public static String capitalizeFully(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    return Arrays.stream(str.split("\\s+"))
            .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
            .collect(Collectors.joining(" "));
}

The only difference between capitalizeAll() and capitalizeFully() is that the latter function explicitly changes the remaining part of the word to lowercase:

System.out.println(capitalizeFully("i aM aTTa")); // I Am Atta
System.out.println(capitalizeFully("fOo bAr")); // Foo Bar

Using String.replaceAll() Method

If you are using Java 9 or higher, it is possible to use a regular expression with the String.replaceAll() method to capitalize the first letter of each word in a string. The String.replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement. Here is an example:

public static String capitalizeAll(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    return Pattern.compile("\\b(.)(.*?)\\b")
            .matcher(str)
            .replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
}

Let us have some examples:

System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
System.out.println(capitalizeAll("i am atta")); // I Am Atta
System.out.println(capitalizeAll(null)); // null

Using Apache Commons Text

The Apache Commons Text library is yet another option to convert the first character of each word in a string to uppercase. Add the following dependency to your build.gradle file:

implementation 'org.apache.commons:commons-text:1.8'

For the Maven project, you need to add the following to your pom.xml file:

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

Now you can use the capitalize() method from the WordUtils class to capitalize each word in a string:

System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
System.out.println(WordUtils.capitalize(null)); // null

The good thing about WordUtils methods is that they handle the exceptions gracefully. There won't be any exception even if the input is null.

The WordUtils class also provides the capitalizeFully() method that capitalizes the first character and turns the remaining characters of each word into lowercase:

System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.