beginnerString ProblemsJava

Capitalize the First Letter of Each Word in a Sentence

Uppercase the first letter of each word in a sentence, leaving other letters unchanged.

Quick Answer

Scan the sentence with a flag that says the next letter starts a new word. Uppercase that first letter, clear the flag, and copy the rest of the word as-is. Every space sets the flag again so the following letter is capitalized. This single pass runs in O(n) time.

Problem Statement

Given a sentence, capitalize the first letter of every word and leave the other letters unchanged. A word begins at the start of the string or right after a space.

For example, hello world becomes Hello World.

Input: A single string s representing a sentence.

Output: The sentence with the first letter of each word capitalized.

Examples

Example 1
Input:  "hello world"
Output: Hello World

The h and w that begin each word are uppercased.

Example 2
Input:  "java is fun"
Output: Java Is Fun

Each word's first letter is capitalized; the rest stay the same.

Constraints

  • 0 <= s.length <= 10^5
  • Only the first letter of each word changes case

Think Before You Code

Reveal the questions to ask yourself first
  • How do you know a character is the first letter of a word?
  • How do you remember that the next non-space character should be capitalized?
  • What happens to the letters that are not at the start of a word?
  • How do spaces reset the "start of word" condition?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
Keep a boolean that says whether the next character starts a new word.
Hint 2
Set that flag true at the beginning and again every time you pass a space.
Hint 3
When the flag is set and you hit a letter, uppercase it and clear the flag.

Approach

Reveal the step-by-step approach

Track word starts with a single flag.

  1. Create a StringBuilder and a boolean capitalizeNext, initialized to true.
  2. For each character c:
    • If c is a space, append it and set capitalizeNext = true.
    • Else if capitalizeNext is true, append Character.toUpperCase(c) and set capitalizeNext = false.
    • Otherwise append c unchanged.
  3. Return the builder's contents.

The flag is on only for the first character of each word, so exactly those letters are uppercased while everything else is copied verbatim.

Dry Run

Walk through the example step by step

Capitalizing "hello world":

char | capitalizeNext | action           | result so far
-----+----------------+------------------+--------------
h    | true           | upper -> H       | H
e    | false          | copy             | He
l    | false          | copy             | Hel
l    | false          | copy             | Hell
o    | false          | copy             | Hello
(sp) | (set true)     | copy space       | "Hello "
w    | true           | upper -> W       | Hello W
o    | false          | copy             | Hello Wo
r    | false          | copy             | Hello Wor
l    | false          | copy             | Hello Worl
d    | false          | copy             | Hello World
final: "Hello World"

Solution

Reveal the full Java solution
public class CapitalizeWords {
    public static String capitalizeWords(String s) {
        StringBuilder sb = new StringBuilder();
        boolean capitalizeNext = true;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                capitalizeNext = true;
                sb.append(c);
            } else if (capitalizeNext) {
                sb.append(Character.toUpperCase(c));
                capitalizeNext = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(capitalizeWords("hello world")); // Hello World
        System.out.println(capitalizeWords("java is fun")); // Java Is Fun
    }
}

The capitalizeNext flag starts true so the very first letter is uppercased, and it is reset to true after every space so the next word's first letter is caught too. When the flag is off, characters are copied unchanged, which preserves any casing that already exists mid-word. Spaces are appended as-is, keeping the original spacing intact.

Time: O(n) where n is the string lengthSpace: O(n) for the output string

Common Mistakes

  • Only capitalizing the first word and forgetting to reset the flag after spaces.
  • Lowercasing the rest of each word when the task only asks for the first letter.
  • Assuming every gap is one space and mishandling multiple spaces.

Edge Cases to Test

  • An empty string returns an empty string.
  • A single word capitalizes just its first letter.
  • A word already capitalized stays correct, like "Java" -> "Java".

Interview Follow-Ups

  • How would you also lowercase the remaining letters to produce strict title case?
  • How would you capitalize the first letter after punctuation, not just spaces?
  • How would you handle tabs and newlines as word separators too?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us