In this short tutorial, we'll get familiar with different options for checking if the first letter of a string is uppercase in Java.
Firstly, we'll start with defining the example string we'll use in all solutions:
String example = "Katie";
So, the example string is just a name that is capitalized. Now, let's inspect the options for checking if the first letter is uppercase.
3. Core Java Solution
The first solution we'll get familiar with does not require a new dependency. We'll use the isUpperCase method from the Character class in the java.lang package:
public static boolean isUpperCase(int codePoint);
This method takes a single character and determines if it is an uppercase character.
For our case, we just need to extract the first character in a string. First, we'll do the extraction with the charAt method. Then, we'll call the isUpperCase method:
This assertion will pass since the first letter in our example string is an uppercase character.
4. Using Regular Expressions
Regular expressions are a common solution when it comes to finding a match in an input string. Therefore, we'll use them to check if the first character in a string is an uppercase.
Like the previous solution, this one doesn't require adding a new dependency. Regular expressions are already available in the java.util.regex package.
The next step is to define the pattern for matching. For our case, we need a pattern that would match if a string starts with an uppercase character while the other characters can be both uppercase, lowercase, or digits. Then, we just need to check if the pattern matches with our example string:
String regEx = "[A-Z]\\w*"; Assertions.assertTrue(example.matches(regEx));
5. Guava Solution
Another solution can be found in the Guava library. We'll need to use the isUpperCase method from the Ascii class to check if the first letter of a string is uppercase.
The first step is to add the Guava dependency:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0.1-jre</version> </dependency>
Then, we'll apply the isUpperCase method to the first letter of our example string:
This approach is practically identical to the core Java solution from chapter 2.1. If there is no particular reason, it is always better to use a solution that doesn't require additional dependencies.
In this article, we've inspected different solutions for checking if the first letter is uppercase.
Firstly, we've discussed a solution available in core Java. Later, we saw how we could perform the checking with regular expressions. Finally, we've presented the solution from the Guava library.
As always, the code for these examples is available over on GitHub.