How to Capitalize the First Letter of a String in Java?
In programming, most of the time we have to deal with a string that is an important part of the programming language. Sometimes, we require to convert the whole paragraph into a sentence case. In such a case, the first letter of the string must be capitalized. So, in this section, we will discuss how to capitalize the first letter of a sting in Java.
In this approach, we will the Java build-in methods substring() and toUpperCase() of the String class.
First, we will define a string whose first letter is to be capitalized. In order to pick the first letter, we have to pass two parameters (0, 1) in the substring() method that denotes the first letter of the string and for capitalizing the first letter, we have invoked the toUpperCase() method.
For the rest of the string, we again called the substring() method and pass 1 as a parameter. It denotes the string after the first letter. At lats concatenate the string to get the result. for example, consider the following code snippet.
Javatpoint Website @javatpoint It is the best website to learn technology.
Using StringUtils.capitalize() Method
Another way to capitalize the first letter of the string is to use StringUtils.capitalize(str) method of the Apache commons lang3 library.
It is a static method of the StringUtils class that is used to convert the first character of the given string to the title case. The remaining characters of the string are not changed.
The method accepts a parameter as final string to be capitalize. It returns the capitalize string.
Download the commons-lang3-3.12.0.jar file or add the following dependency to the pom.xml file.
Robert Jack Tom 'hello'