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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 14, 2019, updated Sep 30, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/capitalize-first-letter-of-each-word-in-string-java

> Learn how to capitalize the first letter of each word in a string in Java using Java 8 Streams, Regular Expression, and Apache Commons Text library.

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](https://attacomsian.com/blog/capitalize-first-letter-of-string-java) 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:

```java
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:

```java
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:

```java
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:

```java
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:

```java
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:

```java
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:

```java
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](http://commons.apache.org/proper/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:

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

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

```xml
<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:

```java
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:

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