How to Make First Letter Capital in Java
In Java, formatting text to make the first letter of each word capital can be useful for creating well-structured and readable code, documentation, or user interfaces. This feature is commonly known as “title casing” or “capitalizing the first letter.” In this article, we will explore various methods to achieve this in Java.
Using String Methods
One of the simplest ways to capitalize the first letter of a word in Java is by using the `String` class’s `substring()` and `toUpperCase()` methods. Here’s an example:
“`java
public class CapitalizeFirstLetter {
public static void main(String[] args) {
String input = “hello world”;
String capitalized = input.substring(0, 1).toUpperCase() + input.substring(1);
System.out.println(capitalized);
}
}
“`
In this code snippet, we create a new string `capitalized` by taking the first character of the input string, converting it to uppercase using `toUpperCase()`, and then concatenating it with the rest of the input string.
Using Regular Expressions
Another approach to capitalize the first letter of each word is by using regular expressions. This method is particularly useful when dealing with strings containing multiple words. Here’s an example:
“`java
public class CapitalizeFirstLetter {
public static void main(String[] args) {
String input = “hello world”;
String capitalized = input.replaceAll(“(^|\\s)[a-z]”, match -> match.group().toUpperCase());
System.out.println(capitalized);
}
}
“`
In this code snippet, we use the `replaceAll()` method with a regular expression that matches the first character of the string or any space followed by a lowercase letter. The `match -> match.group().toUpperCase()` lambda expression is used to replace the matched character with its uppercase equivalent.
Using Apache Commons Text
Apache Commons Text is a widely-used library in Java that provides various utility methods for string manipulation. One of these methods is `WordUtils.capitalizeFully()`, which can be used to capitalize the first letter of each word in a string. Here’s an example:
“`java
import org.apache.commons.text.WordUtils;
public class CapitalizeFirstLetter {
public static void main(String[] args) {
String input = “hello world”;
String capitalized = WordUtils.capitalizeFully(input);
System.out.println(capitalized);
}
}
“`
In this code snippet, we import the `WordUtils` class from the Apache Commons Text library and use the `capitalizeFully()` method to capitalize the first letter of each word in the input string.
Conclusion
In this article, we have explored various methods to capitalize the first letter of a word in Java. By using string methods, regular expressions, or the Apache Commons Text library, you can easily format your text to make it more readable and visually appealing. Choose the method that best suits your needs and preferences to achieve the desired result.