Java - How to capitalize the first letter of a String
In this section, we will show you how to capitalize the first letter of a String.
In Java, we can use str.substring(0, 1).toUpperCase() + str.substring(1) to make the first letter of a String as a capital letter (uppercase letter)
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
//cap = "Java"
or We can use Apache's common library StringUtils.capitalize(str) API to capitalize first letter of the String.
String str = "java";
String cap = StringUtils.capitalize(str);
//cap == "Java"
1. str.substring(0,1).toUpperCase() + str.substring(1)
A complete Java example to capitalize the first letter of a String.
public class Main {
public static void main(String[] args) {
System.out.println(capitalize("knowledgefactory")); // Knowledgefactory
System.out.println(capitalize("java")); // Java
}
// with some null and length checking
public static final String capitalize(String str) {
if (str == null || str.length() == 0)
{
return str;
}
//converts first char to uppercase and adds the remainder of the original string
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
}
Console Output:
Knowledgefactory
Java
2. Using Apache Commons Lang 3, StringUtils.capitalize(str) method
We can use the Apache commons-lang3
library, StringUtils.capitalize(str)
API to capitalize the first letter of a String in Java.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
String str = "java";
String cap = StringUtils.capitalize(str);
System.out.println(cap);
}
}
Console Output:
Java
More related topics,