Java String Program · S13
Capitalize the First Letter of Each Word in Java
Turn "java is fun" into "Java Is Fun". The tricky parts are keeping the exact spacing and not touching the other letters.
Problem Statement
Write a method that returns a copy of a string in which the first character of every word is uppercase. A word starts at the beginning of the string or right after whitespace.
All other characters, including the spacing, stay exactly as they were. An empty string returns an empty string.
Input/Output Examples
"java is fun"Output"Java Is Fun"Explanation: the first letter of each word becomes uppercase." hello world"Output" Hello World"Explanation: the leading and double spaces are kept."iPhone 15 pro"Output"IPhone 15 Pro"Explanation: only first letters change; the digit has no uppercase form.Visual Explanation
"java is fun": only the characters tagged start, the first after a space or at index 0, are converted (purple).The loop keeps one flag, startOfWord, which is true at the beginning and after every whitespace character. The first non-space character after that is uppercased, and the flag turns off until the next space.
Approaches
The loop works character by character. The split approach works word by word and joins the words back together.
Approach 1: StringBuilder Loop (Recommended)
Idea: copy the string into a StringBuilder, uppercasing a character only when it starts a word.
- Set
startOfWord = true. - For whitespace, append it and set
startOfWord = true. - For any other character, append its uppercase form if
startOfWordistrue, otherwise append it unchanged, then set the flag tofalse.
Time: O(n) · Space: O(n). The result has the same length as the input.
Approach 2: split() and join()
Idea: split on single spaces, uppercase the first character of each non-empty piece and join the pieces with a space again.
- Call
split(" ", -1); the-1keeps empty pieces, including trailing ones. - For each non-empty piece, replace it with
toUpperCase(first char) + substring(1). - Join the pieces with
String.join(" ", words).
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: StringBuilder Loop (Recommended)
Every character is copied exactly once, so spaces, tabs and line breaks are preserved. Letters after the first stay as they are.
public class CapitalizeWordsLoop {
// Upper-cases the first character after any whitespace; spacing is kept exactly
static String capitalizeWords(String text) {
StringBuilder result = new StringBuilder(text.length());
boolean startOfWord = true;
for (char c : text.toCharArray()) {
if (Character.isWhitespace(c)) {
startOfWord = true;
result.append(c);
} else {
result.append(startOfWord ? Character.toUpperCase(c) : c);
startOfWord = false;
}
}
return result.toString();
}
public static void main(String[] args) {
String[] inputs = {"java is fun", " hello world", "iPhone 15 pro"};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + capitalizeWords(text) + "\"");
}
}
}
"java is fun" -> "Java Is Fun" " hello world" -> " Hello World" "iPhone 15 pro" -> "IPhone 15 Pro"
Time complexity: O(n) · Space complexity: O(n).
Approach 2: split() and join()
Empty pieces stand for extra spaces, so joining with a single space restores the original spacing. This version splits only on the space character, not on tabs.
public class CapitalizeWordsSplit {
// split(" ", -1) keeps empty pieces, so joining with " " restores the original spacing
static String capitalizeWords(String text) {
String[] words = text.split(" ", -1);
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (!word.isEmpty()) {
words[i] = Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
}
return String.join(" ", words);
}
public static void main(String[] args) {
String[] inputs = {"java is fun", " hello world", "iPhone 15 pro"};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + capitalizeWords(text) + "\"");
}
}
}
"java is fun" -> "Java Is Fun" " hello world" -> " Hello World" "iPhone 15 pro" -> "IPhone 15 Pro"
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| StringBuilder Loop | O(n) | O(n) |
| split() and join() | O(n) | O(n) |
Here n is the length of the string. Both approaches visit each character a constant number of times and build a new string of length n.
Interview Tips and Recommended Approach
- Clarify the rest of the word. Should
"jAVA"become"JAVA"or"Java"? This page keeps the other letters as they are. - Watch for empty pieces.
word.charAt(0)on an empty string throwsStringIndexOutOfBoundsException, which happens with double spaces. - Explain
split(" ", -1). Without the limit, trailing empty strings are removed and trailing spaces are lost. - Test unusual input: leading spaces, several spaces in a row, digits at the start of a word and an empty string.
Recommended Approach: StringBuilder Loop
Why: it reads the string once, preserves every whitespace character exactly and has no empty-string pitfalls. The flag-based loop is also a reusable pattern for other word-boundary problems.