How to capitalize the first letter of a String in Java
In Java, we can use substring(0, 1).toUpperCase() + str.substring(1)
to make the first letter of a String as a capital letter (uppercase letter)
String str = "thecognize";
String str1 = str.substring(0, 1).toUpperCase(); // first letter = T
String str2 = str.substring(1); // after 1 letter = hecognize
String result = str.substring(0, 1).toUpperCase() + str.substring(1); // T + hecognize
Output
Terminal
Thecognize
2. Apache Commons Lang 3, StringUtils
Alternatively, we can use the Apache commons-lang3
library, StringUtils.capitalize(str)
API to capitalize the first letter of a String in Java.
pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
UppercaseFirstLetter.java
package com.thecognize.string;
import org.apache.commons.lang3.StringUtils;
public class UppercaseFirstLetter {
public static void main(String[] args) {
System.out.println(StringUtils.capitalize("thecognize")); // Thecognize
}
}
Output
Terminal
Thecognize