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 Solid
- Getting Started with Svelte
- Getting Started with Electron
- How to deploy a PHP app using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript