How to capitalize first letter in java

In this post, we will how to capitalize first letter in java
[toc]

Capitalize first letter of String

Here are the steps to convert first letter of string to uppercase in java

  • Get first letter of String firstLetStr using str.substring(0,1).
  • Get remaining String remLetStr using str.substring(1).
  • Convert first letter of String firstLetStr to upper Case using toUpperCase() method.
  • Concatenate both the String firstLetStr and remLetStr.
package org.arpit.java2blog;

public class CapitalizeFirstLetterMain {
    public static void main(String[] args) {

        // create a string
        String name = "java2blog";
        System.out.println("Original String: " + name);
        // get First letter of the string
        String firstLetStr = name.substring(0, 1);
        // Get remaining letter using substring
        String remLetStr = name.substring(1);

        // convert the first letter of String to uppercase
        firstLetStr = firstLetStr.toUpperCase();

        // concantenate the first letter and remaining string
        String firstLetterCapitalizedName = firstLetStr + remLetStr;
        System.out.println("String with first letter as Capital: " + firstLetterCapitalizedName);

    }
}

Output:

Original String: java2blog
String with first letter as Capital: Java2blog

Capitalize first letter of each word

Here are the steps to capitalize first letter of each word.

  • Split String by space and assign it String array words
  • Iterate over the String array words and do following:
    • Get first letter of String firstLetter using str.substring(0,1).
    • Get remaining String remainingLetters using str.substring(1).
    • Convert first letter of String firstLetter to upper Case using toUpperCase() method.
    • Concatenate both the String firstLetter and remainingLetters.
package org.arpit.java2blog;

public class CapitalizeFirstLetterMain {
    public static void main(String[] args) {
        // create a string
        String str = "this is java code";
        String words[]=str.split("\\s");
        String capitalizeStr="";

        for(String word:words){
            // Capitalize first letter
            String firstLetter=word.substring(0,1);
            // Get remaining letter
            String remainingLetters=word.substring(1);
            capitalizeStr+=firstLetter.toUpperCase()+remainingLetters+" ";
        }
        System.out.println(capitalizeStr);
    }
}

Output:

This Is Java Code

That’s all about How to capitalize first letter in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.