This post will discuss how to capitalize the first character of each word in a given text in Java.

1. Naive solution

A naive solution is to split the given text using space as a delimiter. Then we iterate through the word array, capitalize the first character of each word, and append it to a StringBuilder along with space. Finally, return the string representation of the StringBuilder.

Download  Run Code

Output:

Techie Delight Is Awesome!

2. Using WordUtils from Apache Commons

The simplest solution is to use the WordUtils class from Apache Commons Lang. It already provides a capitalize() method that serves the same purpose.

Download Code

Output:

Techie Delight Is Awesome!

3. Using Java 8

In Java 8, we can get the stream of the words in the given text, capitalize the first character of each word, and collect it using Collectors.

⮚ Using Pattern.splitAsStream() to get Stream

Download  Run Code

Output:

Techie Delight Is Awesome!

⮚ Using Stream.of() to get Stream

Download  Run Code

Output:

Techie Delight Is Awesome!

 
This is equivalent to:

Download  Run Code

Output:

Techie Delight Is Awesome!

4. Using Guava Library

We can also use the Joiner class from Guava, along with Splitter and Iterables class, as demonstrated below:

Download Code

Output:

Techie Delight Is Awesome!

5. Using Regex

We can also take the help of regular expressions in Java to capitalize the first character of each word, as shown below:

Download  Run Code

Output:

Techie Delight Is Awesome!

That’s all about capitalizing the first character of each word in a Java String.