Skip to content

Capitalize first character of each word of String in Java example

This Java example shows how to capitalize first character of each word of string or make first letter uppercase in Java. The example also shows how to capitalize the first character of each word of String using various approaches.

How to capitalize the first character of each word of String in Java?

To capitalize the first character of each word of String, you can use one of the below given two approaches.

1) Using substring, toUpperCase, and split methods of the String class

We can use the substring, split, and toUpperCase methods of the String class to capitalize the first letter of each word of String as given below.

Output

The above program worked for our sample string. Let’s try some other strings as well.

Inputs

Outputs

As you can see from the output, our program only capitalized words that are separated by space. It ignores all other punctuation marks like comma (,), full stop (.), quotation marks (single quotes and double quotes), hyphens, etc.

In order to include all these characters, we need to change our program a bit. We need to change the split method to split the string by words using the regular expression. We will use \\W pattern which denotes word boundaries.

Here is the updated capitalizeEachWord method.

Inputs

Outputs

I have tested this solution with a limited number of input strings and it worked as expected. It may need some minor tweaks in case if the above method does not work for any particular use case.

2) Capitalize the first character of String using Apache Commons

If you don’t want to implement your own solution, you can always use the ever-reliable Apache Commons library. Use the capitalize or capitalizeFully method of the WordUtils class as given below.

Output

This example is a part of Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.