The Java standard library has provided the String.toUpperCase() method, which allows us to convert all letters in a string to upper case.
In this tutorial, we'll learn how to convert a given string's first character only to upper case.
2. Introduction to the Problem
An example can explain this problem quickly. Let's say we have an input string:
String INPUT = "hi there, Nice to Meet You!";
Given this INPUT string, here's our expected result:
String EXPECTED = "Hi there, Nice to Meet You!";
As we can see, we only want the first character, ‘h‘, to be changed into ‘H‘. However, the remaining characters shouldn't be modified.
Of course, if the input string is empty, the result should be an empty string too:
String EMPTY_INPUT = "";
String EMPTY_EXPECTED = "";
In this tutorial, we'll address several solutions to the problem. For simplicity, we'll use unit test assertions to verify if our solution works as expected.
3. Using the substring() Method
The first idea to solve the problem is to split the input string into two substrings. For example, we can split the INPUT string to “h” and “i there, Nice ….“. In other words, the first substring contains only the first character, and the other substring holds the remaining characters of the strings.
Then, we can just apply the toUpperCase() method on the first substring and concatenate the second substring to solve the problem.
Java's String class's substring() method can help us to get the two substrings:
- INPUT.substring(0, 1) – substring 1 containing the first character
- INPUT.substring(1) – substring 2 holding the rest of the characters
So next, let's write a test to see if the solution works:
String output = INPUT.substring(0, 1).toUpperCase() + INPUT.substring(1);
If we run the test, it passes. However, if our input is an empty string, this approach will raise IndexOutOfBoundsException. This is because the end-index (1) is greater than the empty string's length (0) when we call INPUT.substring(1):
assertThrows(IndexOutOfBoundsException.class, () -> EMPTY_INPUT.substring(1));
Further, we should note that if the input string is null, this approach will throw NullPointerException.
Therefore, before using the substring approach, we need to check and ensure the input string is not null or empty.
4. Using the Matcher.replaceAll() Method
Another idea to solve the problem is to use regex (“^.“) to match the first character and convert the matched group to upper case.
It wasn't an easy task before Java 9. This is because Matcher‘s replacement methods, such as replaceAll() and replaceFirst(), don't support a Function object or a lambda expression replacer. However, this has changed in Java 9.
Since Java 9, Matcher‘s replacement methods support a Function object as the replacer. That is to say, we can use a function to process the matched character sequence and fulfill the replacement. Of course, to solve our problem, we just need to call the toUpperCase() method on the matched character:
String output = Pattern.compile("^.").matcher(INPUT).replaceFirst(m -> m.group().toUpperCase());
The test passes if we give it a run.
If the regex matches nothing, the replacement won't happen. Therefore, this solution works for empty input strings as well:
String emptyOutput = Pattern.compile("^.").matcher(EMPTY_INPUT).replaceFirst(m -> m.group().toUpperCase());
It's worth mentioning that if the input string is null, this solution will throw NullPointerException too. So, we still need to do a null check before we use it.
5. Using StringUtils From Apache Commons Lang 3
Apache Commons Lang3 is a popular library. It ships with a lot of handy utility classes and extends the functionality of the standard Java library.
Its StringUtils class provides the capitalize() method, which solves our problem directly.
To use the library, let's first add the Maven dependency:
Then, as usual, let's create a test to see how it works:
String output = StringUtils.capitalize(INPUT);
The test passes if we execute it. As we can see, we simply call StringUtils.capitalize(INPUT). Then the library does the job for us.
It's worth mentioning that the StringUtils.capitalize() method is null-safe and works for empty input strings as well:
String emptyOutput = StringUtils.capitalize(EMPTY_INPUT);
String nullOutput = StringUtils.capitalize(null);
In this article, we've learned how to convert the first character of a given string to upper case.
As always, the full code used in the article is available over on GitHub.
res – REST with Spring (eBook) (everywhere)