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,

Popular posts from this blog

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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

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

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

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