Java program to capitalize first letter of each word in a string

Java program to capitalize first letter of each word in a String :

In this tutorial, we will learn how to capitalize first letter of each word in a string in Java. User will input one string and then we will capitalize first letter of each word and modify and save the string in a different String variable. Finally, we will output the String.

Java program :

import java.util.Scanner;

public class Main {

    private static void print(String message) {
        System.out.print(message);
    }

    private static void println(String message) {
        System.out.println(message);
    }

    public static void main(String[] args) throws java.lang.Exception {

        //1
        String currentWord;
        String finalString = "";

        //2
        Scanner scanner = new Scanner(System.in);

        //3
        println("Enter a string : ");
        String line = scanner.nextLine();

        //4
        Scanner scannedLine = new Scanner(line);

        //5
        while (scannedLine.hasNext()) {
            //6
            currentWord = scannedLine.next();
            finalString += Character.toUpperCase(currentWord.charAt(0)) + currentWord.substring(1) + " ";
        }

        //7
        println("Final String : " + finalString);
    }

}

Explanation :

The commented number in the above program denotes the steps number below :

1. Create one String variable currentWord to save the current scanned word and one different variable finalString to save the final String.
2. Create one Scanner variable to scan the user input string.
3. Ask the user to enter the string and store it in line variable.
4. Next, create one more Scanner object scannedLine. Note that we are passing line variable while creating this object. So, the Scanner will basically start scanning from this string variable line.
5. Start one while loop and scan the line word by word.
6. Store the current word in string variable currentWord. This while loop will read word by word. We are changing the first character to upper case of a word and then adding the next letters of that word. And,finally we are adding one space after that word. So, for example, the word hello will become Hello .
7. After the loop is completed, we have the result string stored in variable finalString. So, print out the final string finalString.

Example Output :

Enter a string :
this is a test string
Final String : This Is A Test String

Leave a Reply