“String” is a data type in Java that describes a sequence of characters. This sequence can be in uppercase, lowercase, or mixed letter case. Capitalizing the first letter of strings (like names, sentences, etc.) is a standard convention. Other than this, there can be many other cases where capitalizing the string’s first letter may be needed, such as formatting, string sorting, managing user input, etc. To deal with such cases, Java offers several methods of built-in classes and third-party libraries.
In this article, you’ll learn different methods of capitalizing a string’s first letter/character in Java.
How to Capitalize the First Letter of a String in Java
You can capitalize the string’s first character in Java by using one of the following methods:
- Method 1: Using substring().toUpperCase()
- Method 2: Using Matcher.replaceFirst()
- Method 3: Using StringUtils.capitalize()
- How to Convert the First Letter/Character of Each Word to Uppercase in Java
- How to Convert the Whole String Into Uppercase in Java
Method 1: Using substring().toUpperCase()
To capitalize the first character of a string using the substring() method, follow the following algorithm:
- First extract the string’s first letter using the “substring(0, 1)” method. Then, capitalize it using the “toUpperCase()” method. Store this substring in a string-type variable, e.g., “substring1”.
- Next, use the “substring(1)” method to extract all characters of the given string except the first character. Store this substring in another string-type variable, e.g., “substring2”.
- Join both the substrings using the “+” operator to get the desired capitalized string.
Let’s learn this concept practically using Java programming:
public class CapitalizeFirstLetter {
public static void main(String[] args) {
String inputStr = "hi geeks, welcome to javabeat";
String substring1 = inputStr.substring(0,1).toUpperCase();
String substring2 = inputStr.substring(1);
String capitalizeStr= substring1+substring2;
System.out.println("Original String == " + inputStr);
System.out.println("capitalized String == " + capitalizeStr);
}
}
We create a Java class “CapitalizeFirstLetter” and it’s main() method declares a string “inputStr”. Next, we invoke the substring() method with two parameters “0 and 1”. As a result, this method extracts a substring from the 0th index to the 1st index. We invoke the toUpperCase() method on this extracted string to capitalize it. After this, we call the substring() method again, but this time with one parameter only, i.e., “1”. As a result, it extracts the complete string except the specified index, i.e., 1. Finally, we combine both the extracted substrings and print the resultant string on the console:
The output shows that the string’s first letter has been successfully capitalized.
Method 2: Using Matcher.replaceFirst()
Follow the below-listed steps to capitalize the string’s first letter using the “Mathcer.replaceFirst()” method:
- Create a regex pattern “^.” using the “Pattern.compile()” method to match the first letter.
- Use the “matcher.replaceFirst()” method with the toUpperCase() method to replace the first letter of the string with the corresponding uppercase letter.
The following code implements the above-stated steps in Java to capitalize the string’s first letter:
import java.util.regex.*;
public class CapitalizeFirstLetter {
public static String capLetter(String inputStr) {
Pattern regex = Pattern.compile("^.");
String capStr = regex.matcher(inputStr).replaceFirst(str -> str.group().toUpperCase());
return capStr;
}
public static void main(String[] args) {
String inputStr = "let's learn Java with javabeat.net";
System.out.println("Original String == " + inputStr);
String capitalizedStr = capLetter(inputStr);
System.out.println("Capitalized String == " + capitalizedStr);
}
}
In this code, first, we import the required classes like “Pattern” and “Matcher” from the “java.util.regex” package. Next, we create a user-defined “capLetter” function that accepts the input string as an argument and retrieves a capitalized string. Within this function, we use the compile() method to create a regex pattern to capitalize the given string. After this, we use the “matcher().replaceFirst()” function to convert the first letter of the input string to uppercase. Finally, we invoke the capLetter() function from the main() method to get the desired capitalized string on the console:
Method 3: Using StringUtils.capitalize()
StringUtils class belongs to the “Apache Commons” library which offers numerous utility methods for efficient string manipulation. One such method is capitalize() which converts/changes the string’s first character to capital/uppercase. To use this method, you must add the following dependency for Apache Commons to your Maven project:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Now import the “StringUtils” class from the Apache Commons Lang to use its “capitalize()” method:
import org.apache.commons.lang3.StringUtils;
public class CapitalizeFirstLetter {
public static void main(String[] args) {
String inputStr = "javabeat.net";
System.out.println("Original String == " + inputStr);
String capitalizedStr = StringUtils.capitalize(inputStr);
System.out.println("Capitalized String == " + capitalizedStr);
}
}
In the main() method, first, we declare a string variable and initialize it with “javabeat.net”. After this, we invoke the “StringUtils.capitalize()” method on the input string to make its first letter capital. Finally, we print the input and capitalized strings on the console:
How to Convert the Whole String Into Uppercase in Java
To convert a string’s all letters to uppercase, use/invoke the “toUpperCase()” method on the given string using a dot syntax:
public class CapitalizeFirstLetter {
public static void main(String[] args) {
String inputStr = "welcome to javabeat.net";
System.out.println("Original String == " + inputStr);
System.out.println("Capitalized String == " + inputStr.toUpperCase());
}
}
The output shows that the stated method converts each letter of the input string into uppercase:
How to Convert the First Letter/Character of Each Word to Uppercase in Java
Java supports multiple methods to convert the first character of each word into uppercase, such as “toUpperCase()”, “WordUtils.capitalizeFully()”, etc.
We use the toUpperCase() method with some other methods of the Arrays and Collectors class to convert the first letter of each word to uppercase:
import java.util.Arrays;
import java.util.stream.Collectors;
public class CapitalizeFirstLetter {
public static String capitalizedStr(String inputStr) {
return Arrays.stream(inputStr.split(" ")).map(str -> str.substring(0,1).toUpperCase()+str.substring(1)).collect(Collectors.joining(" "));
}
public static void main(String[] args) {
String inputStr = "welcome to javabeat.net";
System.out.println("Original String == " + inputStr);
System.out.println("Capitalized String == " + capitalizedStr(inputStr));
}
}
First, we create a user-defined function that takes the input string as an argument and converts the first letter of each word into uppercase. Within this function, we employ the split() method with a space ” ” as the delimiter/splitter to break the input string into an array of substrings. We wrap the split() method within the “Arrays.stream()” method to convert the array of words into a stream. Also, we use the map() method with the “substring().toUpperCase()” method to alter the first character/letter of each word into uppercase. In the end, we use the “Collectors.joining(” “)” method to join each modified word with a whitespace. Finally, we collect the stream elements into a single String and return it:
That’s all about capitalizing the string’s first letter in Java.
Final Thoughts
To capitalize the string’s first letter/character in Java, you can use methods like “substring().toUpperCase()”, “Matcher.replaceFirst()”, or “StringUtils.capitalize()”. The first two methods are plain Java methods that are directly accessible without adding any dependency. While the “StringUtils.capitalize()” belongs to a third-party “Apache Commons” Library and is accessible after adding its corresponding dependency, as illustrated in this post.