Capitalize First Letter of Each Word in Java — Definition, Examples and Program

Learn how to capitalize the first letter of each word in a string in Java using character-level logic without using built-in string manipulation methods.

Capitalize First Letter of Each Word in Java

Capitalizing the first letter of each word is a common string manipulation task used in formatting names, titles, and sentences.

In this program, we process the string character by character without using built-in string formatting methods.

Understanding the Problem

Given a sentence, we need to:

Example 1

Input: java is fun

Output: Java Is Fun

Example 2

Input: welcome to kodekraftt

Output: Welcome To Kodekraftt

Logic Explanation

  1. Convert the string into a character array.
  2. Capitalize the first character if it is lowercase.
  3. Whenever a space is found, capitalize the next character.
  4. Append characters to form the final string.

Java Program to Capitalize First Letter of Each Word


import java.util.Scanner;

public class CapitalizeWords {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        String str = sc.nextLine();

        char[] ch = str.toCharArray();

        for (int i = 0; i < ch.length; i++) {

            if (i == 0 && ch[i] >= 'a' && ch[i] <= 'z') {
                ch[i] = (char)(ch[i] - 32);
            } 
            else if (ch[i] == ' ' && i + 1 < ch.length) {

                if (ch[i + 1] >= 'a' && ch[i + 1] <= 'z') {
                    ch[i + 1] = (char)(ch[i + 1] - 32);
                }
            }
        }

        System.out.print("Formatted string: ");
        System.out.println(ch);
    }
}

Sample Output


Enter a sentence: java is fun
Formatted string: Java Is Fun

Important Notes

Practice Challenges

  1. Convert the rest of each word to lowercase.
  2. Capitalize words separated by special characters.
  3. Ignore extra spaces at the beginning and end.

This program improves understanding of character manipulation and ASCII-based conversions in Java.