How to Capitalize the First Letter of a String in Java

Updated onbyAlan Morel
How to Capitalize the First Letter of a String in Java

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.

JAVA
String 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.

JAVA
public 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:

JAVA
public 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.

JAVA
String 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.