Capitalize the first letter of a string in Java
In this quick tutorial, you will learn how to capitalize the first letter of a string in Java. Unfortunately, the String class does not provide any method to capitalize strings. However, there are methods available to change the case of the string (uppercase, lowercase, etc.).
The simplest way to capitalize the first letter of a string in Java is by using the String.substring() method:
String str = "hello world!"; // capitalize first letter String output = str.substring(0, 1).toUpperCase() + str.substring(1); // print the string System.out.println(output); // Hello world!
The above example transforms the first letter of string str to uppercase and leaves the rest of the string the same. If the string is null or empty, the above code throws an exception. However, we can write a functional capitalize() that makes sure the string has at least one character before using the substring() method:
public static String capitalize(String str) if(str == null || str.isEmpty()) return str; > return str.substring(0, 1).toUpperCase() + str.substring(1); >
Now just call the capitalize() method whenever you want to make the first letter of a string uppercase:
System.out.println(capitalize("hello world!")); // Hello world! System.out.println(capitalize("heLLo")); // HeLLo System.out.println(capitalize(null)); // null
Notice the 2nd line of the above code snippet, only the first letter is capitalized. If you want to ensure only the first letter is in uppercase and the remaining string is lowered case, you can do the following:
str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase()
The Apache Commons Lang library is another way to capitalize the first letter of a string in Java. If you are using Gradle, add the following dependency to your build.gradle file:
implementation 'org.apache.commons:commons-lang3:3.9'
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.9version> dependency>
The StringUtils class from Commons Lang provides the capitalize() method to change the first letter to uppercase:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons System.out.println(StringUtils.capitalize("heLLO")); // HeLLO System.out.println(StringUtils.uncapitalize(null)); // null
Apache Commons Lang offers many extra methods that are not included in standard Java libraries ( java.lang package). It includes String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization, and System properties.
In this article, we looked at different ways to capitalize the first letter of a string in Java. The simple approach is to use the String class’s substring() method. However, if you are already using Apache Commons Lang in your project, just use the StringUtils class to capitalize the first letter of a string. Since string capitalization is a common task in all programming languages, I have also written a tutorial to do the same in JavaScript. Take a look at this guide. Read Next: Capitalize the first letter of each word in a string using Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Capitalize the First Letter of a String in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
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); assertEquals(EXPECTED, output);
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()); assertEquals(EXPECTED, output);
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()); assertEquals(EMPTY_EXPECTED, emptyOutput);
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:
org.apache.commons commons-lang3 3.12.0
Then, as usual, let’s create a test to see how it works:
String output = StringUtils.capitalize(INPUT); assertEquals(EXPECTED, output);
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); assertEquals(EMPTY_EXPECTED, emptyOutput); String nullOutput = StringUtils.capitalize(null); assertNull(nullOutput);
6. Conclusion
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.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: