This post will discuss how to capitalize the first letter of a String in Java.

1. Using String.toUpperCase() method

The idea is to extract the first character from the string and convert it to uppercase by calling the toUpperCase() method. Once we have converted the first character to uppercase, use the string concatenation operator to concatenate it with the remaining string.

Note that since the String is immutable in Java, no modifications can be done to the actual string. The solution creates a new string instance. The following code demonstrates this using the substring() method.

Download  Run Code

Output:

Capitalize me

 
If the string is empty, then the above program throws a StringIndexOutOfBoundsException. If the string is null, NullPointerException is thrown. The following program creates a utility method to capitalize a string that handles both these exceptions:

Download  Run Code

Output:

Capitalize me

2. Using StringUtils.capitalize() method

Another solution is to use the StringUtils class from Apache Commons Lang library. It already provides a capitalize() method that serves the same purpose.

Download Code

Output:

Capitalize me

2. Using WordUtils.capitalize() method

If you need to capitalize the first character of each word in a string, you should use the capitalize() method from the WordUtils class.

Download Code

Output:

IKEA Store

 
If you need to capitalize the first character and convert the remaining characters of each word to lowercase, use the capitalizeFully() method instead.

Download Code

Output:

Ikea Store

4. Using Stream API

Alternatively, with Java 8, you can get a stream of all whitespace-separated words, and capitalize each word using the same approach discussed before in this post. The following solution demonstrates this.

Download  Run Code

Output:

Capitalize Me

That’s all about capitalizing the first letter of a String in Java.