Table of Contents
In this post, we will learn how to capitalize the first letter of a string in Java.
Java does not provide this functionality natively, so we must write our own by using other methods available to us.
substring()
The easiest way to capitalize the first letter of a string in Java is by using the substring() method.
Specifically, we can use the substring() method to get the first letter of a string and then capitalize it, then concatenate the rest of the string.
JAVAString text = "welcome to Sabe.io!";
String firstLetter = text.substring(0, 1);
String capitalizedFirstLetter = firstLetter.toUpperCase();
String restOfText = text.substring(1);
String capitalizedText = capitalizedFirstLetter + restOfText;
System.out.println(capitalizedText);
// Welcome to Sabe.io!
We can get the first letter of a string by using the substring() method and passing in the index of the first letter, then the end index.
From there we simply capitalize the first letter by using toUpperCase().
Finally, we take the capitalized letter and then concatenate the rest of the string.
Java Method
Our implementation works, however if the string is empty or null, we will get an error. We can fix this by checking if the string is empty or null before we try to use the substring() method.
Let's create a new method that safely capitalizes the first letter of a string.
JAVApublic static String capitalizeFirstLetter(String text) {
if (text == null || text.isEmpty()) {
return "";
}
String firstLetter = text.substring(0, 1);
String capitalizedFirstLetter = firstLetter.toUpperCase();
String restOfText = text.substring(1);
String capitalizedText = capitalizedFirstLetter + restOfText;
return capitalizedText;
}
Or written more compactly:
JAVApublic static String capitalizeFirstLetter(String text) {
if (text == null || text.isEmpty()) {
return "";
}
return text.substring(0, 1).toUpperCase() + text.substring(1);
}
Now we can use this method any time you want to capitalize the first letter of a string.
JAVAString text = "welcome to Sabe.io!";
String capitalizedText = capitalizeFirstLetter(text);
System.out.println(capitalizedText);
// Welcome to Sabe.io!
Conclusion
We've seen how to make the first letter of a string uppercase in Java. You can either create a standalone method or do it manually whenever you need to.
Hopefully this post has been helpful to you!
Getting Started with Solid
Managing PHP Dependencies with Composer
Create an RSS Reader in Node
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to deploy an Express app using Docker
How to deploy a Node app using Docker
Getting Started with Sass
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
