Start learning free

LESSON 218 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Capitalize Each Word in Java: split, substring and join

Practice Read the full explanation

Given a string sentence, return the same sentence with the first letter of each word in upper case.

The words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes: the rest of the word stays exactly as it is, even when it has upper-case letters. A first character that has no upper case, like a digit, stays as it is too.

 

Example 1:

Input: sentence = "hello world"
Output: "Hello World"
Explanation: h becomes H and w becomes W.

Example 2:

Input: sentence = "learn to code with AlgoCademy"
Output: "Learn To Code With AlgoCademy"
Explanation: AlgoCademy already starts with an upper-case letter, so it stays the same.

Example 3:

Input: sentence = "iPhone and NASA"
Output: "IPhone And NASA"
Explanation: Only the first character of each word changes: "Phone" and "ASA" stay as they were.

 

Constraints:

  • sentence has at least one word.
  • sentence contains English letters, digits and apostrophes, with single spaces between the words.
STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in Java, explained

    Problem overview

    The method capitalizeWords receives a sentence and returns it with the first character of every word in upper case. Words are separated by single spaces, and the sentence has no space at the start or end. Only the first character of each word changes. The rest of the word stays as it is, even when it contains upper-case letters, and a first character that has no upper case, such as a digit, stays too.

    "hello world" becomes "Hello World". "iPhone and NASA" becomes "IPhone And NASA": the Phone in iPhone and the ASA in NASA are untouched.

    Approach: split, fix each word, join

    Break the sentence into words, capitalize the first character of each, then put the words back with the same spaces. Splitting at single spaces and joining with single spaces restores every space exactly where it was.

    Step by step

    1. Split the sentence with sentence.split(" ") into a String[] named words.
    2. Create an empty List<String> named result, a new ArrayList, to collect the fixed words in order.
    3. Loop over words with an enhanced for loop and a String variable word.
    4. Build the capitalized word: word.substring(0, 1) is the first character, toUpperCase() converts it, and word.substring(1) is everything after it.
    5. Add the new word to result.
    6. Join the words with String.join(" ", result) and return the text.

    The solution in Java

    class Solution {
        public String capitalizeWords(String sentence) {
            String[] words = sentence.split(" ");
            List<String> result = new ArrayList<>();
            for (String word : words) {
                String capitalized = word.substring(0, 1).toUpperCase() + word.substring(1);
                result.add(capitalized);
            }
            return String.join(" ", result);
        }
    }
    

    Running it gives these results:

    InputOutput
    "hello world""Hello World"
    "learn to code with AlgoCademy""Learn To Code With AlgoCademy"
    "iPhone and NASA""IPhone And NASA"
    "5th avenue""5th Avenue"

    Java details:

    • Strings are immutable. Methods such as toUpperCase and substring return new strings and never change the original, which is why the method builds a new list instead of editing words.
    • substring(start) versus substring(start, end). The end index is exclusive, so substring(0, 1) is the first character only. substring(1) runs to the end of the string.
    • One-letter words. For "a", substring(1) is the empty string. It is legal because the start index equals the length. Indexes beyond the length throw an exception.
    • Digits. toUpperCase on "5" gives "5", so a word like 5th keeps its first character.
    • String.join takes a separator and any collection of strings, so it works on the List<String> directly.

    Another way to upper-case the first letter

    The first character can also be handled as a char: Character.toUpperCase(word.charAt(0)) + word.substring(1) gives IPhone for iPhone. Here charAt(0) returns a char, and adding a String to it afterwards works because the + with a String on one side does string concatenation. Beware of adding two char values, which adds their numeric codes. The substring(0, 1) form used in the lesson stays a String throughout, which avoids that trap.

    Edge cases and common mistakes

    • Lower-casing the rest. Calling toLowerCase() on word.substring(1) would turn NASA into Nasa. The task keeps it as NASA.
    • A double space. The task promises single spaces. If a sentence had two in a row, split(" ") would produce an empty string between them, and substring(0, 1) on it would throw a StringIndexOutOfBoundsException.
    • A single word. "hello".split(" ") gives an array with one element, so the method works for it unchanged.
    • Capitalizing only the first word. The loop has to run over every element of words.

    Testing

    • "hello world" gives "Hello World".
    • "a b" gives "A B".
    • "iPhone and NASA" gives "IPhone And NASA".
    • "5th avenue" gives "5th Avenue".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free