How to Capitalize the First Letter of a String in Java
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 TypeScript
- Getting Started with Solid
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue