Capitalize the first letter of every array elements in Java

Hello, coders today we are going to learn how to capitalize the first letter of every array elements in Java.

EXPLANATION:

First, we will create an array having elements with their first letter in Lowercase.

strArray={“one”, “two”, “three”, “four”, “five”, “six” }

So above is the array of String which we are going to be working on.

Next, we will create a for loop and a function to call each word inside the strArray array.

Now we will print for each element in each loop in an array of string.

After this, the function will return a new copy of str but with the first letter as capital.

For More better and clear understanding go through the code below.

Java Program to Capitalize The First Letter Of Every  Array Elements

The below Java program will convert the first letters of the array elements to uppercase letters.

public class Capital {
    public static void main(String[] args) {
        String[] strArray = {"one", "two", "three", "four", "five", "six" }; // Creating Array of String.

        // Call firstLetterCapital function for each word inside strArray array.
        for (int i = 0; i < strArray.length; i++) {
            strArray[i] = firstLetterCapital(strArray[i]);
        }

        //This for each loop will print each element in array of string.
        for(String str:strArray) {
            System.out.println(str);
        }
    }

    // This function will return new copy of str (input string) but with first letter as capital.
    // Notice this function is static because we going to call this function from main method. and main method is static.
    static String firstLetterCapital(String str) {
        String firstLetter =  str.substring(0,1);  //Take first letter as new string,
        // this done with help of substring method of String class.

        String firstLetterCapital = firstLetter.toUpperCase();

        String strExcludeFirstLetter = str.substring(1, str.length());

        // Final string will be firstLetterCapital followed by strExceptFirstLetter.

        String result = firstLetterCapital + strExcludeFirstLetter;

        return result;
    }

}

INPUT:

{"one", "two", "three", "four", "five", "six" }

OUTPUT:

{"One", "Two", "Three", "Four", "Five", "Six" }

So, in this way, we can convert the first letter of every array elements to capital or uppercase letter in Java.

Also, learn:

Leave a Reply

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