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,

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java, Spring Boot Mini Project - Library Management System - Download

Java - Blowfish Encryption and decryption Example

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete

Java - DES Encryption and Decryption example

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Top 5 Java ORM tools - 2024

Java - How to Count the Number of Occurrences of Substring in a String