How to Capitalize First Letter in Java

In this post, we will learn How to Capitalize First Letter in Java Programming Language. Let’s understand Strings in Java and about methods of the String class in Java.

Let’s see the How to Capitalize First Letter in Java.

How to Capitalize First Letter in Java

import java.util.*;

public class Main{
    
    public static void main(String[] args){
        
        Scanner sc = new Scanner(System.in);
        String word = sc.next();
        
        //getting the firstLetter
        String firstLetter = word.substring(0,1);
        
        //word after removing first letter
        String substr = word.substring(1);
        
        // Capitalizing the first letter and attaching it back to the substring 
        String capWord = firstLetter.toUpperCase() + substr;
        
        System.out.println(capWord);
    }
    
}

Output

Enter the word : asgard 
Asgard

How Does This Program Work?

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the word : ");
        String word = sc.next();

In this program, we first take input of the word from the user using the Scanner Class.

        //getting the firstLetter
        String firstLetter = word.substring(0,1);

Then, we split the first letter from the given string using the substring(0,1) function to split the substring from string from index 0 to index 1(exclusive), i.e. 1-1 = 0, so by this we get the first letter removed and we store it in the variable named firstLetter.

        //word after removing first letter
        String substr = word.substring(1);

Then, we stored the rest split sub-string without the first letter in the variable substr.

        // Capitalizing the first letter and attaching it back to the substring 
        String capWord = firstLetter.toUpperCase() + substr;

Then, using the toUpperCase() function we capitalize string. We capitalize the first letter and concatenate it back to the substring and make the work back with the capitalized first letter.

  System.out.println(capWord);

Then, we display the new string with capitalized first letter in it. This is the Java Program to Capitalize first letter of String.

This is How to Capitalize First Letter in Java.

Conclusion

I hope after going through this post, you understand How to Capitalize First Letter in Java. We learned the Java Program to Capitalize the First Letter of String.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.

Also Read:

Leave a Comment

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