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 = "mkyong";

String str1 = str.substring(0, 1).toUpperCase();  // first letter = M

String str2 = str.substring(1);     // after 1 letter = kyong

String result = str.substring(0, 1).toUpperCase() + str.substring(1); // M + kyong

Table of contents:

1. substring(0,1).toUpperCase() + str.substring(1)

A complete Java example to capitalize the first letter of a String, and a null and length checking.

UppercaseFirstLetter.java

package com.mkyong.string;

public class UppercaseFirstLetter {

  public static void main(String[] args) {

      System.out.println(capitalize("mkyong"));   // Mkyong
      System.out.println(capitalize("a"));        // A
      System.out.println(capitalize("@mkyong"));  // @mkyong

      //String capitalize = StringUtils.capitalize(str);
      //System.out.println(capitalize);

  }

  // with some null and length checking
  public static final String capitalize(String str) {

      if (str == null || str.length() == 0) return str;

      return str.substring(0, 1).toUpperCase() + str.substring(1);

  }

}

Output

Terminal

Mkyong
A
@mkyong

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.mkyong.string;

import org.apache.commons.lang3.StringUtils;

public class UppercaseFirstLetter {

    public static void main(String[] args) {

        System.out.println(StringUtils.capitalize("mkyong"));   // Mkyong
        System.out.println(StringUtils.capitalize("a"));        // A
        System.out.println(StringUtils.capitalize("@mkyong"));  // @mkyong

    }

}

Output

Terminal

Mkyong
A
@mkyong

3. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-string

4. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Maikel
10 months ago

Thanks for your content. Always help me